Skip to content

Instantly share code, notes, and snippets.

@szajbus
Last active December 18, 2015 05:29
Show Gist options
  • Save szajbus/5733058 to your computer and use it in GitHub Desktop.
Save szajbus/5733058 to your computer and use it in GitHub Desktop.
Strange behavior of == in Ruby 1.8.7

This gist shows buggy behavior of == in Ruby 1.8.7. This affects case equality (===) too because by default === calls == internally unless redefined in specific class (like Range or Regexp).

class A
  def ==(other)
    puts "In A: calling == against #{other}"
    super
  end
end

class E < Exception
  def ==(other)
    puts "In E: calling == against #{other}"
    super
  end
end

Example 1

"foo" == A.new
=> false

Nothing interesting here, move along.

Example 2

"foo" == E.new
In E: calling == against foo
=> false

Calling == on String triggers == on other object of Exception class.

Example 3

42 == A.new
In A: calling == against 42
=> false

Calling == on Fixnum triggers == on other object.

Example 4

42 == E.new
In E: calling == against 42
=> false

Calling == on String triggers == on other object of Exception class.


  1. Why calling == on String or Fixnum triggers calling == on other object at all?
  2. Why calling == on String works differently depending on the other object class?

In Ruby 1.9+ calling == on other object is not triggered, bug has been fixed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment