I want to implement ==
for a ruby class. I can do
def ==(o)
o.respond_to?(:id) && self.id == o.id
end
or
def ==(o)
o.is_a?(Foo) && self.id == o.id
end
According to this article, it seems that the former would make more sense. If I was implementing eql?
then I would do the latter. Is this correct?
It depends if you're comparing to an arbitrary object or one of a specific type. The second form is specific, the first generic.
In your case you're probably fine with the specific form. Generic comparisons are only relevant when the object you're comparing with can be converted or interpreted as something that can match. Using id
seems way too open ended. This would imply that Foo 10 and Bar 10 are equivalent when they might be drawn from completely different sources.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With