For a simple struct-like class:
class Tiger
attr_accessor :name, :num_stripes
end
what is the correct way to implement equality correctly, to ensure that ==
, ===
, eql?
, etc work, and so that instances of the class play nicely in sets, hashes, etc.
EDIT
Also, what's a nice way to implement equality when you want to compare based on state that's not exposed outside the class? For example:
class Lady
attr_accessor :name
def initialize(age)
@age = age
end
end
here I'd like my equality method to take @age into account, but the Lady doesn't expose her age to clients. Would I have to use instance_variable_get in this situation?
To simplify comparison operators for objects with more than one state variable, create a method that returns all of the object's state as an array. Then just compare the two states:
Also, if you want instances of your class to be usable as a hash key, then add:
These need to be public.
Usually with the
==
operator.To test all your instance variables equality at once: