在比较密钥时,Ruby的Hash使用哪种相等性测试?

ale*_*loh 6 ruby hash equality equals

我有一个围绕一些对象的包装类,我想用它作为哈希中的键.包装和解包对象应映射到同一个键.

一个简单的例子是:

class A
  attr_reader :x
  def initialize(inner)
    @inner=inner
  end
  def x; @inner.x; end
  def ==(other)
    @inner.x==other.x
  end
end
a = A.new(o)  #o is just any object that allows o.x
b = A.new(o)
h = {a=>5}
p h[a] #5
p h[b] #nil, should be 5
p h[o] #nil, should be 5
Run Code Online (Sandbox Code Playgroud)

我试过==,===,eq?哈希都无济于事.

Mar*_*une 5

您必须定义eql?hash

Hash缺少相关文档,但最近有所改进


aro*_*ero 5

哈希使用key.eql吗?测试密钥是否相等。如果需要将自己的类的实例用作哈希中的键,建议您同时定义两个eql?和哈希方法。哈希方法必须具有a.eql?(b)暗示a.hash == b.hash的属性。

所以...

class A
  attr_reader :x
  def initialize(inner)
    @inner=inner
  end
  def x; @inner.x; end
  def ==(other)
    @inner.x==other.x
  end

  def eql?(other)
    self == other
  end

  def hash
    x.hash
  end
end
Run Code Online (Sandbox Code Playgroud)