Skip navigation

Equality in Ruby

Just so you know:

  • == a.k.a. value equality
  • eql? a.k.a. value and type equality
  • equal? a.k.a. object identity
  • === a.k.a. case equality

Object identity should never be overridden. It compares object ids, always.

When overriding, start with value equality. If you’re not doing type conversions then you can simply add “alias :eql? :==”. I was surprised to learn that eql? doesn’t call == or vice versa (by default).

Case equality defaults to calling value equality, but you can do handy stuff by providing a custom interpretation. This is what makes ruby’s case statement so powerful Notable examples are Class, where it tests if the object is an instance of the class, and Regexp, where it tests if the string matches. Because of this your can write

  case p
  when Symbol;...;end
  when Class;....;end
  end

or

  case str
  when /\A\d+\z/
    ...
  end
  end

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*