Difference between <=> and == in Ruby?
Asked Answered
N

3

6

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?

Nunn answered 24/7, 2011 at 20:24 Comment(0)
P
14

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

Pentathlon answered 24/7, 2011 at 20:28 Comment(1)
Ah, so <=> is like Java's compareTo() method?Nunn
C
3

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

Crenelation answered 24/7, 2011 at 20:33 Comment(0)
H
2

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

Hageman answered 24/7, 2011 at 20:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.