class A
def hash
12
end
def ==(other)
true
end
end
x = {}
a = A.new
b = A.new
x[a] = "Hello"
x[b] = "World"
puts x
This is printing:
{#<A:0x000055d1f3985c68>=>"Hello", #<A:0x000055d1f3985830>=>"World"}
I expected replacement, not happening, why?
Two objects are treated as the same hash key when their
hash
value is identical and the two objects areeql?
to each other.
http://www.ruby-doc.com/3.3.0/Hash.html#class-Hash-label-Hash+Key+Equivalence
You have to define eql?
instead of ==
:
class A
def hash
1
end
def eql? other
true
end
end
x = {}
a = A.new
b = A.new
x[a] = "Hello"
x[b] = "World"
p x
#=> {#<A:0x00007fce035af608>=>"World"}