Reputation: 3371
I have class Foo
, and I overload two of its methods ==
and eql?
:
class Foo
def initialize(bar)
@bar = bar
end
def bar
@bar
end
def ==(o)
self.bar == o.bar
end
def .eql?(o)
return ==(o)
end
end
I test that f1
and f2
below are equal with respect to the two methods:
u = User.find(12345)
f1 = Foo.new(u)
f2 = Foo.new(u)
f1 == f2 # => true
f1.eql?(f2) # => true
But Hash#has_key?
does not render them equal:
{f1 => true}.has_key?(f2) # => false
What is the equality method used in Hash#has_key?
?
Upvotes: 1
Views: 110
Reputation: 30453
It uses hash
method. You may concatinate properties of your objects there or something like that. In your case you want hash value to be the same for 2 objects if and only if they are equal.
Upvotes: 2
Reputation: 224922
Most implementations of a hash type, Ruby’s included, rely on a hash first (for speed!) and then equality checks. To verify that it works, first, you can just add
def hash
1
end
After that, you should work on providing as many possible distinct return values for hash
that will still be equal if the objects are considered equal (as long as it’s fast, of course).
Upvotes: 2