。零?附加到数组时的值查询

时间:2013-05-10 19:03:45

标签: ruby if-statement null

我正在进行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?

这条线是否要求:

“如果我刚输入的标题已经在电影数组中表示为符号,那么这个声明是假的吗?”

在这种情况下,我想如果标题不存在,if语句将评估为true,如果标题已存在则为false。如果电影确实是新的,那么最后,只需要询问

中所述的相关信息
else

语句。如果有人能帮助澄清我的误解,我将非常感激!

1 个答案:

答案 0 :(得分: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