ruby - Ruby 的 Hash 在比较键时使用哪种相等性测试?

标签 ruby hash equals equality

我有一个围绕一些对象的包装类,我想将这些对象用作散列中的键。包装对象和解包装对象应映射到相同的键。

一个简单的例子是这样的:

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

关于ruby - Ruby 的 Hash 在比较键时使用哪种相等性测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11247000/

相关文章:

ruby - 在 ruby​​ 中释放对象的最佳实践

ruby-on-rails - 附加的图像没有用回形针保留

perl - 关于 Perl 中哈希排序和打印的问题

java - 任何 HashMap 方法都不会调用覆盖的 hashCode() 函数

java - 我如何表达两个值彼此不相等?

ruby - 在Ruby编程语言中,$:叫什么名字

mysql - 已安装 C MySQL gem 时使用基于 Ruby 的 MySQL 适配器?

java - 我如何生成字符串的长散列?

c# - 哈希算法 SHA256,我的方法安全吗?如何添加盐值以使其更安全

java - 覆盖父类(super class) Equals 和 HashCode 并认为我应该对子类做同样的事情