Friday, October 19, 2007

Ruby Equality: Useful To Remember

>> [1,2] == [1,2]
=> true
>> [1,2].equal? [1,2]
=> false

8 comments:

  1. And, also:

    >> [1,2].eql? [1,2]
    => true

    WTF, mate?

    ReplyDelete
  2. How about this one:
    >> 'a' === String
    => false
    >> String === 'a'
    => true

    ReplyDelete
  3. .eql? is an .equal? only relevant to numeric comparison.

    ReplyDelete
  4. [1,2] == [2,1] #=> false on my machine

    ReplyDelete
  5. === is not commutative petrik. That's by design, since its main use is for the case... when statement.
    brian, [1,2] and [2,1] are obviously not equal. Order is meaningful in arrays.

    ReplyDelete
  6. One of them is a *by value* comparison, and one of them is a *by reference* comparison; Matz's ripped this straight out of Lisp (but Java/C# has this too).

    '==' is saying "Do these objects have the same value?", and 'equal?' is saying "Are these two the same object in memory". Since they were created in separate parts of the expression, and they aren't memoized, the latter is False (internally, these two arrays are stored in different places).

    If you picked non-integral types, '==' will always be the same as 'equal?'.

    ReplyDelete
  7. Ah ok that makes sense. Thanks!

    ReplyDelete
  8. Here is nice catch:

    require 'ostruct'

    [1, 2].to_set == [2, 1].to_set
    => true

    ReplyDelete

Note: Only a member of this blog may post a comment.