我正在做关于 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.to_sym] = rating.to_i
puts "Your info was saved brah!"
case movies
when 'add'
puts "What movie do you want to add son?"
title = gets.chomp
if movies[title.to_sym].nil?
puts "What's your new rating brah?"
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"
if movies[title.to_sym].nil?
when "display"
puts "Movies!"
when "delete"
puts "Deleted!"
else puts "Error!"
end
我只是指 add 方法。脚本的其余部分正在进行中。我不喜欢不理解事物,这让我有点困惑。
我的问题是 Ruby 是否知道不添加已经存在的标题,因为两个符号不能具有相同的名称?我很好奇它如何确定哈希何时没有价值。任何人都可以为我澄清这一点吗?我真的很感激!