1

我正在完成 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

陈述。如果有人能帮助澄清我的误解,我将不胜感激!

4

1 回答 1

6

.nil?询问您发送nil?消息的对象是否实际上是nil.

'a string'.nil? #=> false
nil.nil?        #=> true

x = 'a string'
x.nil?          #=> false

x = nil
x.nil?          #=> true

您对if movies[title.to_sym].nil?条件如何工作的理解基本上是正确的。默认情况下,如果值不在散列中,则散列将返回nil.

movies = { GIS: 10.0, Phantasm: 1.5, Bourne: 4.0 }

# Ignoring the user input
title = 'Bourne'

movies[title.to_sym].nil?
#=> movies["Bourne".to_sym].nil?
#=> movies[:Bourne].nil?
#=> 4.0.nil?
#=> false

movies[:NoSuchMovie].nil?
#=> nil.nil?
#=> true
于 2013-05-10T19:12:12.610 回答