title: Object Equality in Ruby description: > How to implement equality correctly in Ruby. categories: posts
In order to have a correct object equality we need to implement these
three methods: #==
, #eql?
, #hash
.
Assume #item_name
, and #qty
are all the public values in an object.
Given #==
should check equality based on the attribute values of two objects:
def ==(other)
item_name == other.item_name && qty == other.qty
end
When it comes to checking equality via uniqueness, we need to define #eql?
.
def eql?(other)
hash == other.hash
end
#hash
is expected to return unique values, since they are used when putting
an object in or out of a Set
, Hash
, and the like.
def hash
self.item_name.hash ^ self.qty.hash
end
Beware that since hashes should be unique we need to make sure the hashes we produce don't collide with those produce by others.