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?
This means… For example, by defining == you can tell Ruby how to compare two objects of the same class.
In Ruby, the === operator is used to test equality within a when clause of a case statement.
== operator The '==' operator checks whether the two given operands are equal or not. If so, it returns true.
Unlike the == operator which tests if both operands are equal, the equal method checks if the two operands refer to the same object. This is the strictest form of equality in Ruby. In the example above, we have two strings with the same value. However, they are two distinct objects, with different object IDs.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With