我正在做编解码器的练习,我不知道是什么。没有意思是我被要求去执行它这是我的代码:
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?
询问所附声明是否为假我困惑的症结在于:
if movies[title.to_sym].nil?
这句话是在问:
“如果我刚输入的标题已经在movies数组中表示为符号,那么这句话是否为false?”
在这种情况下,我假设如果标题不存在,如果if已经存在,则if语句将被评估为true。如果这部电影确实是新的,那么它最后只需要按照
else
陈述。如果有人能帮助澄清我的误解,我将非常感激!
最佳答案
.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