Object Equality in Ruby

A curious feature to be aware about Ruby.

o1 = Object.new

o2 = Object.new

Now if we ask the console whether

o1 == o2

then what do you think we will get as a response? True or false?

Strangely, we get false!

Apparently, according to Ruby, the two objects are not equal. Why?

Because they are actually two different objects!

Explanation by Example

Imagine you have a Toyota Camry that is blue in your drive way. Now imagine that you’ve gone out and purchase another blue Toyota Camry and parked it on your drive way as well. Now you have two cars sitting there.

Is Car1 the same as Car2?

Well, it’s not the same car – they are actually different cars. But they are the same type of car.

Watch out: there are exceptions

Best read the documentation if there is any uncertainty. More than likely, when you require a clear answer, it’s worth referring to.

http://ruby-doc.org/core-2.4.0/Object.html#method-i-eql-3F

Summary:

  • equal? shouldn’t be overriden. This asks whether the two objects are the same object.
  • == in this case a == b can return true even if a and b are different objects. This can be a little confusing so
  • You gotta check out the documentation whenever you run into these types of issues.

I hope you gained something from this. Be careful of what you expect when you check for Object equality.

Written on February 18, 2017