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

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

一个简单的例子是:

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

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

解决方法

Hash uses key.eql? to test keys for equality. If you need to use
instances of your own classes as keys in a Hash,it is recommended
that you define both the eql? and hash methods. The hash method must
have the property that a.eql?(b) implies 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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...