What are their differences? Coming from a Java background, it does seem to me <=> is the same as Java's equals(), while == is for direct reference comparison. Is this right?
The major difference between the == operator and . equals() method is that one is an operator, and the other is the method. Both these == operators and equals() are used to compare objects to mark equality.
Well in short: == inherently converts type and === does not convert type. Double Equals ( == ) checks for value equality only. It inherently does type coercion. This means that before checking the values, it converts the types of the variables to match each other.
The == operator checks if two values are equal. The != operator checks if two values are not equal. It is also known as the loose equality operator because it checks abstract equality, i.e., it tends to convert the data types of operands in order to carry the comparison when two operands aren't of the same data type.
Summary. The key difference is different usage. Use equal to compare values strictly, while if you want to compare objects use eql , which is equivalent to deep equal.
==
only measures if two objects are equal, whereas <=>
should return -1 if the first object is smaller, 0 if they are equal, and 1 if the first object is greater.
If you define a <=>
method for your class, you'll get all of the other comparison operators defined as well (==
, <
, >
, and so on).
Can't say I'm not trying to promote myself, but I wrote a full length tutorial about comparison and equality operators in Ruby: "Ruby Basics – Equality operators in Ruby"
In there you can see the differences between all the equality operators, including <=>, == and === (and the implications of implementing them, including the hash method implementation).
==
is like Java's equals
, while <=>
is like compareTo
. ==
compares the two objects and returns whether they are equivalent. a <=> b
compares the two objects and returns 1 if a
is bigger, 0 if they are the same and -1
if b
is bigger.
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