在比较键时,Ruby的散列使用哪个等式测试?

时间:2021-10-15 14:26:37

I have a wrapper class around some objects that I want to use as keys in a Hash. The wrapped and unwrapper objects should map to the same key.

我在一些对象上有一个包装器类,我想把它们用作散列中的键。包装好的和未包装的对象应该映射到相同的键。

A simple example will be this:

一个简单的例子就是:

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

I've tried ==, ===, eq? and hash all to no avail.

我试过=== =而哈希也没用。

2 个解决方案

#1


4  

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.

散列使用key.eql ?测试平等的关键。如果您需要在散列中使用自己的类的实例作为键,那么建议您定义两个eql?和散列方法。哈希方法必须具有a.eql (b)的属性。散列= = b.hash。

So...

所以…

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

#2


4  

You must define eql? and hash.

您必须定义eql吗?和散列。

The documentation of Hash was lacking but has been improved recently.

散列的文档缺乏,但最近有所改进。

#1


4  

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.

散列使用key.eql ?测试平等的关键。如果您需要在散列中使用自己的类的实例作为键,那么建议您定义两个eql?和散列方法。哈希方法必须具有a.eql (b)的属性。散列= = b.hash。

So...

所以…

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

#2


4  

You must define eql? and hash.

您必须定义eql吗?和散列。

The documentation of Hash was lacking but has been improved recently.

散列的文档缺乏,但最近有所改进。