» Ruby Equality! equal? eql? == and ===

The equality methods in ruby confuse me about once a month. So it's time to permanently embed this information into my brain.

The first confusing part is remembering which object is doing the comparing.

1 == 2
# It makes more sense if you think of it like this
1.==(2)

1 calls it's method == with the argument 2. I like to think of it as 1 is put in charge of checking if it equals 2. 2 is just along for the ride.The second confusing part is there are several methods that deal with equality but in a slightly different ways.

equal?

Returns true if the object_id's are equal. Rarely used, and should not be overridden. You can basically forget out it.

a = b = "bob"
a.equal? b # true

a.equal? "bob" # false since the object_id for the literal "bob" is different than will be different

==

The most common equality operator. It is generally used to test the value of objects instead of the object_id's.

string = "bob"
array = [1,2,3]

array == [1,2,3] # true
string == "bob" # true
1 == 1.0 # true

eql?

Just like == but more strict (i.e. returns false for objects are different types.) As far as I can tell, this is only used to compare hash keys. Like the equal? method, you can basically forget about this one.

string = "bob"
string.eql? "bob" # true
1.eql? 1.0 # false since 1 is a Fixnum and 1.0 is a Float

===

Used for case statements. It is full of magic and sprinkled with mystery. This case statement...

case 1
when Numeric then "Number"
when String then "String"
end

# It is equivalent to...
if Numeric === 1 then "Number"
elsif String === 1 then "String"
end

This seems kind of unintuitive since the arguments for === seem to be in the reversed in the case statement. But this technique has more power than greyskull. Check out Regex, Range, and Module to see clever === uses. Also remember a === b may be true, but it's converse b === a could be false!

User Comments

Recent Posts

  • Interactive console for iOS! - August 20, 2010
  • Archive

    • Letter to Steve Jobs - April 11, 2010
    • Wax talks to Twitter - October 20, 2009
    • How does iPhone Wax work? - October 19, 2009
    • Setting up iPhone Wax - October 18, 2009
    • Ruby (tinyrb) on iPhone - May 03, 2009
    • Building PCRE static lib for the iPhone - May 02, 2009
    • Amazon EC2 + Chef = Mmmmm - March 29, 2009
    • Objective-c key paths - February 13, 2009
    • POW! - December 26, 2008
    • Abusing Ruby's question mark methods. - November 28, 2008
    • Git hooks make me giddy - November 07, 2008
    • Ruby Equality! equal? eql? == and === - October 26, 2008
    • Ruby, Rails and Google Sitemaps - October 20, 2008
    • Projects

      • Wax Obj-C to Lua bridge for iPhone.
      • Pow a Ruby library for making file & directory manipulation easy.
      • MiniMagick a tiny RMagick replacement.