Today I discovered Ruby doing something unexpected with the ==
operator. With a class like this:
class Value # ... initialize, other methods, etc. ... def ==(other) self.a_method == other.a_method end end
and a test that effectively evaluated the expression:
3 == Value.new(args)
I expected a message saying that Value
couldn’t be coerced to Fixnum
. Instead I got
undefined method `a_method' for 3:Fixnum (NoMethodError)
I thought that 3 == Value.new(args)
was equivalent to 3.==(Value.new(args))
, yet this message suggests Ruby is evaluating Value.new(args).==(3)
. It’s almost as if Ruby has decided that ==
is commutative. How can that happen? I was obviously missing something. Continue reading Commutative equality in Ruby?