Which equality test does Ruby's Hash use when comparing keys? -
i have wrapper class around objects want use keys in hash. wrapped , unwrapper objects should map same key.
a simple example this:
class attr_reader :x def initialize(inner) @inner=inner end def x; @inner.x; end def ==(other) @inner.x==other.x end end = a.new(o) #o object allows o.x b = a.new(o) h = {a=>5} p h[a] #5 p h[b] #nil, should 5 p h[o] #nil, should 5
i've tried ==, ===, eq? , hash no avail.
hash uses key.eql? test keys equality. if need use instances of own classes keys in hash, recommended define both eql? , hash methods. hash method must have property a.eql?(b) implies a.hash == b.hash.
so...
class 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
Comments
Post a Comment