MΓ³dulo 24 Β· The Ruby Object Model β LecciΓ³n 6 de 6 Β· ~11 min
Equality, Comparison & Copies (Capstone)
Three kinds of "equal" β and when each fires
"Are these equal?" has three answers in Ruby, and mixing them up causes real bugs (duplicate hash keys, sets that don't dedupe):
equal?β identity. Same object in memory. Never override it.==β value equality. "Do these represent the same thing?" Override this for your own value objects.eql?β the stricter equality used byHashkeys, together withhash. Two objects that areeql?must return the samehash.
In an interview, say: "
equal?is identity,==is value equality you define, andeql?+hashare the Hash-key contract. If I override==for a value object, I overrideeql?andhashtoo, or it'll behave wrong as a hash key or in a Set."