Reputation: 77416
In Java, ==
is the strongest kind of equality (pointer equality): a == b
always implies a.equals(b)
. However, in Ruby, ==
is weaker than .equals?
:
ruby-1.9.2-rc2 > 17 == 17.0
=> true
ruby-1.9.2-rc2 > 17.equal?(17.0)
=> false
So, where can I learn more about ==
? What kind of checks should I expect when I compare two objects with it?
Upvotes: 9
Views: 4179
Reputation: 46965
briefly this is what you need to know:
The ==
comparison checks whether two values are equal
eql?
checks if two values are equal and of the same type
equal?
checks if two things are one and the same object.
A good blog about this is here.
Upvotes: 8
Reputation: 44080
==
is, simply, a method. I think it is explained really well here:
Typically, this method is overridden in descendent classes to provide class-specific meaning.
along with an example with Numeric
s.
There's a pitfall here, though: as ==
is a method of the left operand, it is not always safe to assume that the result of a==b
should be the same as of b==a
. Especially in cases when a
is a method call, which, in a dynamic language such as Ruby, must not always return values of the same type.
Upvotes: 1
Reputation: 14671
jruby-1.5.0 > 17 ==17
=> true
jruby-1.5.0 > 17 == 17.0
=> true
jruby-1.5.0 > 17 === 17.0
=> true
jruby-1.5.0 > 17.equal?(17.0)
=> false
jruby-1.5.0 > 17.id
=> 35
jruby-1.5.0 > (17.0).id
(irb):12 warning: Object#id will be deprecated; use Object#object_id
=> 2114
Everything in ruby is an object. the object 17 is not the same object as 17.0 and equal? compares objects, not values of objects.
Upvotes: 0
Reputation: 66711
in reality they're both just methods == means object.==(other_object) equals? means object.equals?(other_object)
In this case, though, equals is used basically for hash lookup comparison i.e. a_hash[1] should not be the same key value pair as a_hash[1.0]
HTH. -r
Upvotes: 1