我试图创建一个'to_hash'数组方法,但不断出现"堆栈级别太深"的错误:
class Array
def to_hash
Hash[self.each_index.zip(self)]
end
end
puts [50, 49, 53, 44].to_hash
# SystemStackError: stack level too deep
我终于发现方法名称"to_hash"导致了问题。只需将其更改为"to_hsh"即可使其按预期工作:
class Array
def to_hsh
Hash[self.each_index.zip(self)]
end
end
puts [50, 49, 53, 44].to_hsh
# => {0=>50, 1=>49, 2=>53, 3=>44}
如果我尝试在数组上调用"to_hash"方法(不编写自己的方法),我会得到:
NoMethodError: [50, 49, 53, 44] 的未定义方法 'to_hash' :数组
因此,如果没有内置的数组"to_hash"方法,为什么将自己的数组方法命名为"to_hash"会遇到问题?
因为内核#哈希方法调用to_hash
.这会导致递归调用。
文档说:
通过调用 arg.to_hash 将 arg 转换为哈希。当 arg 为 nil 或 [] 时返回空哈希。
在第 Hash[self.each_index.zip(self)]
行中,self.each_index.zip(self)
生成一个数组,Kernel#Hash
正在该数组上调用to_hash
。现在,此to_hash
成为您的自定义to_hash
方法,这是一个递归调用,并产生堆栈级别太深的错误(SystemStackError)。