Wednesday, 13 February 2008

Equality in Ruby - == eql? and equal?

The == comparison checks whether two values are equal

eql? checks if two values are equal and of the same type

equal? checks if two things are one and the same object.

How do I remember which is which ... The longer the operator, the more restrictive the test it performs

Example:

irb(main):013:0> val = 17
=> 17
irb(main):014:0> val == 17.0
=> true
irb(main):015:0> val.eql?(17.0)
=> false
irb(main):016:0> val.eql?(17)
=> true
irb(main):017:0> val.equal?(17)
=> true
(written 2006-12-14 16:49:47)

1 comment:

pawelstawicki said...

There is also "===" operator, which is even more bizzare. 1 === [0..5] => true. In this case it checks if number is in range.

I really like ruby, but there are too many equality operators. It's just confusing.