【发布时间】:2018-05-28 22:44:03
【问题描述】:
给定这个脚本
def hash
puts "why?"
end
x = {}
x[[1,2]] = 42
输出如下
why?
/tmp/a.rb:6:in `hash': no implicit conversion of nil into Integer (TypeError)
from /tmp/a.rb:6:in `<main>'
在这种情况下,脚本中定义的hash 函数似乎覆盖了Array#hash。由于我的hash 方法的返回值是nil 而不是Integer,因此它会引发异常。以下脚本似乎证实了这一点
puts [1,2,3].hash
def hash
puts "why?"
end
puts [1,2,3].hash
输出是
-4165381473644269435
why?
/tmp/b.rb:6:in `hash': no implicit conversion of nil into Integer (TypeError)
from /tmp/b.rb:6:in `<main>'
我尝试查看 Ruby 源代码,但无法弄清楚为什么会发生这种情况。是否记录了这种行为?
【问题讨论】:
-
我没有得到这种行为。
class Array; def hash; nil; end; end; puts [1,2,3].hash打印一个空行并为我返回 nil。x[[1,2]] = 1仍然会引发 TypeError,但x[nil] = 1工作正常。确实很奇怪的行为..你在用什么红宝石版本?我正在使用 2.3.1
标签: ruby