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

前端之家收集整理的这篇文章主要介绍了在比较密钥时,Ruby的Hash使用哪种相等性测试?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个围绕一些对象的包装类,我想用它作为哈希中的键.包装和解包对象应映射到同一个键.

一个简单的例子是:

  1. class A
  2. attr_reader :x
  3. def initialize(inner)
  4. @inner=inner
  5. end
  6. def x; @inner.x; end
  7. def ==(other)
  8. @inner.x==other.x
  9. end
  10. end
  11. a = A.new(o) #o is just any object that allows o.x
  12. b = A.new(o)
  13. h = {a=>5}
  14. p h[a] #5
  15. p h[b] #nil,should be 5
  16. 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.

所以…

  1. class A
  2. attr_reader :x
  3. def initialize(inner)
  4. @inner=inner
  5. end
  6. def x; @inner.x; end
  7. def ==(other)
  8. @inner.x==other.x
  9. end
  10.  
  11. def eql?(other)
  12. self == other
  13. end
  14.  
  15. def hash
  16. x.hash
  17. end
  18. end

猜你在找的Ruby相关文章