我正在完成 codecademy 练习,但我无法弄清楚 .nil 是什么?意味着我需要执行它的方式。这是我的代码:
movies = { GIS: 10.0, Phantasm: 1.5, Bourne: 4.0}
puts "Whats your movie brah?"
title = gets.chomp
puts "What's your rating brah?"
rating = gets.chomp
movies[title] = rating
puts "Your info was totally saved brah!"
case movies
when 'add'
puts "What movie do you want to add?"
title = gets.chomp
if movies[title.to_sym].nil?
puts "What's the rating? (Type a number 0 to 4.)"
rating = gets.chomp
movies[title.to_sym] = rating.to_i
puts "#{title} has been added with a rating of #{rating}."
else
puts "That movie already exists! Its rating is #{movies[title.to_sym]}."
end
when "update"
puts "Updated!"
when "display"
puts "Movies!"
when "delete"
puts "Deleted!"
else puts "Error!"
end
我正在为每个以“add”命令开头的命令创建方法。不过,让我完全困惑的是
.nil?
据我了解,nil = false
所以,我在想的是
.nil?
正在询问所附陈述是否为假。我的困惑的症结在于:
if movies[title.to_sym].nil?
那条线是在问:
“如果我刚刚输入的标题已经在 movies 数组中表示为一个符号,那么这个说法是假的吗?”
在这种情况下,我想如果标题不存在,if 语句将评估为 true,如果它已经存在,则评估为 false。如果这部电影确实是新电影,它最后会简单地询问相关信息,如
else
陈述。如果有人能帮助澄清我的误解,我将不胜感激!