刚开始学习Ruby;为什么我的代码在Codeacademy环境中正常工作,但在Mac终端中却不能正常工作?



完成一个关于哈希的小项目;符号,并想看看它在终端上是如何运行的。

它在Codeacademy中执行得很好,但在终端中打印出错误的响应,似乎是因为它没有正确引用哈希数组。

尽管我输入的终端不存在于哈希数组中,它还是打印出"它已经在列表上了!">

是codeacademy教我不正确,还是我的代码有一些特定于终端的问题?

movies = {
Hackers: 8.0,
Gladiator: 9.0,
}
puts "Would you like to add, update, display, or delete movies?"
choice = gets.chomp
case choice
when "add"
puts "What's the movie called?"
title = gets.chomp.to_sym
puts "What would you rate it out of 10?"
rating = gets.chomp.to_i
if movies[title.to_sym] = nil
movies[title.to_sym] = rating.to_i
puts "The movie has been added!"
else puts "It's already on the list!"
end

=是赋值操作符,==是比较操作符。=操作符用于为变量赋值,==操作符用于比较两个变量或常量。了解它们的区别是很重要的,代码学院的环境可能是造成这个问题的原因。Ruby也有一个===运算符。

movies = {
Hackers: 8.0,
Gladiator: 9.0,
}
puts "Would you like to add, update, display, or delete movies?"
choice = gets.chomp
case choice
when "add"
puts "What's the movie called?"
title = gets.chomp.to_sym
puts "What would you rate it out of 10?"
rating = gets.chomp.to_i
if movies[title.to_sym] == nil
movies[title.to_sym] = rating.to_i
puts "The movie has been added!"
else 
puts "It's already on the list!"
end

最新更新