Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a "==" implementation in Ruby check the type?

Tags:

equality

ruby

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?

like image 739
Amir Raminfar Avatar asked Nov 14 '22 05:11

Amir Raminfar


1 Answers

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.

like image 118
tadman Avatar answered Dec 06 '22 16:12

tadman