比较键时,Ruby的Hash使用哪个相等测试? [英] Which equality test does Ruby's Hash use when comparing keys?

查看:93
本文介绍了比较键时,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.

推荐答案

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆