Equality in
Ruby
Romain Sempé
@rsempe
Equality or Identity?


—  Equality:
       Different objects that represent the same value.


—  Identity:
       Different variables that refer to the same object.
Equal yes! But in what sense?

—  What equality methods should we use?
    —  ==
    —  eql?
    —  equal?
    —  ===
    —  =~
==
Test only if the objects have the same value.
eql?
Test if the objects have the same value and the
                    same type.
equal?
Test if the objects have the same value, the same
  type and are the same instance in memory.
===
    Same as == but for case statements.
One operator depending on the context of the
  comparison (Class, Range, Regexp, …).
=~
Interesting with the Regexp class.
It’s an alias to the match method.
Conclusion

—  == is great most of the time

—  eql? and equal? can be useful to be more precise

—  Elegant case statements with ===

—  Concise test for Regexp with =~

—  Only one identity operator: equal?

Equality in Ruby

  • 1.
  • 2.
    Equality or Identity? — Equality: Different objects that represent the same value. —  Identity: Different variables that refer to the same object.
  • 3.
    Equal yes! Butin what sense? —  What equality methods should we use? —  == —  eql? —  equal? —  === —  =~
  • 4.
    == Test only ifthe objects have the same value.
  • 5.
    eql? Test if theobjects have the same value and the same type.
  • 6.
    equal? Test if theobjects have the same value, the same type and are the same instance in memory.
  • 7.
    === Same as == but for case statements. One operator depending on the context of the comparison (Class, Range, Regexp, …).
  • 8.
    =~ Interesting with theRegexp class. It’s an alias to the match method.
  • 9.
    Conclusion —  == isgreat most of the time —  eql? and equal? can be useful to be more precise —  Elegant case statements with === —  Concise test for Regexp with =~ —  Only one identity operator: equal?