This is confusing. Why does this happen?
2.0 == 2 # => true
2.0.eql? 2 # => false
This is confusing. Why does this happen?
2.0 == 2 # => true
2.0.eql? 2 # => false
because ruby tries to do a type-conversion with ==
but not with eql?
... and like @sawa said - it'd be inconvenient if that were not an option available to us. Comparing 0.0
with 0
for instance is really useful, and most of the time, whether an object is an int or a decimal doesn't really matter. (is 30
minutes the same as 30.0
minutes? do we care that one has .0
on the end?)
Your question asks:
This is confusing. Why does this happen?
2.0 == 2 # => true 2.0.eql? 2 # => false
This is documented behavior.
At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendant classes to provide class-specific meaning...Numeric types, for example, perform type conversion across ==, but not across eql?
The documentation even gives these examples to illustrate:
1 == 1.0 #=> true
1.eql? 1.0 #=> false
In contrast, Float#eql? says:
Returns true only if obj is a Float with the same value as float. Contrast this with Float#==, which performs type conversions.