本文介绍了比较键时,Ruby的Hash使用哪个相等测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包装类,用于包装一些要用作哈希键的对象.包装和解包的对象应映射到相同的键.

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.

推荐答案

所以...

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的Hash使用哪个相等测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 15:14