Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between <=> and == in Ruby?

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?

like image 365
devoured elysium Avatar asked Jul 24 '11 20:07

devoured elysium


People also ask

What is difference between == and equals () show with example?

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.

What is the difference between == and === signs?

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.

What is the difference between == and === operators?

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.

What is the difference between EQL and equal?

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.


3 Answers

== 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).

like image 108
Rafe Kettler Avatar answered Sep 23 '22 08:09

Rafe Kettler


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).

like image 37
Maurício Linhares Avatar answered Sep 23 '22 08:09

Maurício Linhares


== 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.

like image 25
BaroqueBobcat Avatar answered Sep 23 '22 08:09

BaroqueBobcat