简体   繁体   English

ruby哈希作为哈希的关键

[英]ruby hash as key to a hash

Came across the following weird behaviour in ruby 1.8.6, in 1.8.7 it seems to be working correctly. 在ruby 1.8.6中遇到以下奇怪的行为,在1.8.7中它似乎正常工作。 Does anyone know what would have caused this? 有谁知道会造成什么?

h = {}
key_1 = {1 => 2}
key_2 = {1 => 2}
h[key_1] = 3
p key_1 == key_2 # => true
p h.has_key?(key_2) # => expect true, get false, wtf?

I had thought that it would be caused by the implementation of the hash method on the Hash class. 我原以为它是由哈希类上哈希方法的实现引起的。

p [key_1.hash, key_2.hash] # => [537787070, 537787060] (different)

but even if I override the hash method of Hash 但即使我重写哈希的哈希方法

class Hash
  def hash
    return self.keys.hash + self.values.hash
  end
end

p [key_1.hash, key_2.hash] # => [8,8] (same
p h.has_key?(key_2)        # => false

codepad link to online ruby 1.8.6 interpreter results: http://codepad.org/7nCYMP4w codepad链接到在线ruby 1.8.6解释器结果: http//codepad.org/7nCYMP4w

The answer is because in Ruby 1.8.6 the hash coding algorithm was broken for hash keys. 答案是因为在Ruby 1.8.6中,散列编码算法被破解了。

http://paulbarry.com/articles/2009/09/14/why-rails-3-will-require-ruby-1-8-7 http://paulbarry.com/articles/2009/09/14/why-rails-3-will-require-ruby-1-8-7

Edit: Here is an example that shows that ruby does not call .hash internally: 编辑:这是一个示例,显示ruby不会在内部调用.hash:

 class Hash
    def hash
       raise
    end
 end

 {1=>1}.hash
 RuntimeError: 
from (irb):12:in `hash'
from (irb):17

 h = {1=>2}
 {1=>2}
 h[1]
 2

Ruby 1.8.6 is broken in this respect, and if there were a pure Ruby way to do it (such as opening Hash , people would do it. It was fixed in 1.8.7 Ruby 1.8.6在这方面已经被打破了,如果有一种纯Ruby方式可以做到(比如打开Hash ,人们就会这样做。它在1.8.7中得到修复)

这在1.8.7+中得到修复,但是您可以使用补丁1.8.6做正确的操作,例如: https//github.com/rdp/sane/blob/master/lib/sane/hash_hashes.rb

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM