I've been reading about the differences between eql?
and ==
in ruby, and I understand that ==
compares the values while eql?
compares the value and the type
According to the ruby docs:
For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition, but there are exceptions.
It does not seem like the behavior specified in the docs is automatically inherited, but rather this is just a suggestion of how to implement these methods. Does this also imply that if you override either ==
or eql?
then you should override both?
In the class Person
below, is this the typical way of overridding eql?
and ==
, where the less restrictive ==
just delegates to the more restrictive eql?
(it would seem backwards to have eql?
delegate to ==
if ==
was only implemented to compare values and not types).
class Person
def initialize(name)
@name = name
end
def eql?(other)
other.instance_of?(self.class) && @name == other.name
end
def ==(other)
self.eql?(other)
end
protected
attr_reader :name
end