The Ruby Object class has three methods that can tell you if two objects are exactly the same or not. The method names are ’==’. eql?, and equal?
To see how these methods work, fire up the Ruby irb, and create two objects as follows:
>> a = Object.new
=> #<Object:0x521c644c>
>> b = Object.new
=> #<Object:0x701d4bf9>
Then compare the first object against itself – they should be the same.
>> a == a
=> true
>> a.eql?(a)
=> true
>> a.equal?(a)
=> true
Then compare the first object against second – they should be different.
>> a == b
=> false
>> a.eql?(b)
=> false
>> a.equal?(b)
=> false
Of the three equality methods that come with Object the ’==’ is probably the strangest looking one. Yes, ’==’ is a method name !! It’s part of the larger family of Ruby equality-test methods that includes ==, >, <, >=, and <=.
Not every Ruby class that you create will or should have all these methods, but for those that do there is a quick way to get all of them:
- Create a class and Mix in a module called Comparable (which comes with Ruby).
- Define a comparison method with the name <=> in your class.
For example, let’s say you are a farmer and you want to track the weight of your Heffers. Then you might create a Heffer class with a comparable method as follows:
class Heffer
include Comparable
attr_accessor :weight
def <=>(other_heffer)
if self.weight < other_heffer.weight
-1
elsif self.weight > other_heffer.weight
1
else
0
end
end
end
A return value of -1 means less then, a return value of 1 means greater than, and a return value of 0 means equal.
The beauty of this is that all you have to do is add the comparison method <=> and Ruby has all it needs to provide the other comparison methods for you.