Ruby 为什么在调用错误的散列名称时它会进入正确的分支?
我是学习Ruby的新手。在下面的代码中,我犯了一个错误,写了一个错误的单词“Ruby 为什么在调用错误的散列名称时它会进入正确的分支?,ruby,hash,Ruby,Hash,我是学习Ruby的新手。在下面的代码中,我犯了一个错误,写了一个错误的单词“hash”,而不是“movies”。但我发现这也是正确的方法。为什么会发生这种情况 有人能给我解释一下吗 movies = {:Frozen => 9} puts "input a movie title:" title = gets.chomp puts "the rating of the movie:" rating = gets.chomp if hash[title.to_i].nil? #here,i
hash
”,而不是“movies
”。但我发现这也是正确的方法。为什么会发生这种情况
有人能给我解释一下吗
movies = {:Frozen => 9}
puts "input a movie title:"
title = gets.chomp
puts "the rating of the movie:"
rating = gets.chomp
if hash[title.to_i].nil? #here,i wrote 'hash' instead of 'movies'
movies[title.to_sym] = rating.to_i
puts "Added successfully!"
else
puts "The movie already exists."
end
以下是我的输入和运行结果:
为什么散列[title.to_i]
似乎不是零,仍然显示“电影已经存在。
”
input a movie title:
Frozen
the rating of the movie:
4
The movie already exists.
您正在调用
main的hash
方法
p self # => main
p self.methods.sort #=> [:!, :!=, :! ... :hash,...]
p self.hash # => -1928951575263865998
title.to_i
-这背后的逻辑是什么?哦,顺便说一句,方法hash
存在于所有对象上。对了,我认为它在main
上调用hash
,它返回一个Fixnum
,然后它对该Fixnum
进行整数偏移,返回一个非零值。