在比较密钥时,Ruby的Hash使用哪种相等性测试?
发布时间:2020-12-16 20:54:29 所属栏目:百科 来源:网络整理
导读:我有一个围绕一些对象的包装类,我想用它作为哈希中的键.包装和解包对象应映射到同一个键. 一个简单的例子是: class A attr_reader :x def initialize(inner) @inner=inner end def x; @inner.x; end def ==(other) @inner.x==other.x endenda = A.new(o) #o
我有一个围绕一些对象的包装类,我想用它作为哈希中的键.包装和解包对象应映射到同一个键.
一个简单的例子是: 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?哈希都无济于事. 解决方法
所以… 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |