Difference between <=> and == in Ruby?

What are their differences? Based on the Java background, it seems to me that <=> matches Java equals (), and == - for direct comparison of links. Is it correct?

+6
source share
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 larger.

If you define a <=> method for your class, you also define all other comparison operators ( == , < , > , etc.).

+14
source

I can’t say that I’m not trying to promote myself, but I wrote a complete tutorial on comparison and equality operators in Ruby: "Fundamentals of Ruby - Equality Operators in Ruby"

Here you can see the differences between all equality operators, including <=>, == and === (and the consequences of their implementation, including the implementation of the hash function method).

+3
source

== is similar to Java equals , and <=> is similar to compareTo . == compares two objects and returns their equivalent. a <=> b compares two objects and returns 1 if a greater, 0 if they are the same, and -1 if b greater.

+2
source

Source: https://habr.com/ru/post/893461/


All Articles