Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 为什么在调用错误的散列名称时它会进入正确的分支?_Ruby_Hash - Fatal编程技术网

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

我是学习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 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
进行整数偏移,返回一个非零值。