The <=> operator in Ruby

Possible duplicate:
What is Ruby <=> (spaceship)?

I saw a code and an operator that I am not familiar with

  @array << {:suffix=> substring, :index => i} @array.sort! { |x,y| x[:suffix] <=> y[:suffix]} 

I can not use Google. What does <=> do?

+4
source share
3 answers

This comparison is specific to a particular class. If so, that ... < ... true, it returns -1 , if ... == ... true, then 0 , and if ... > ... is true, then 1 .

+4
source

This is a spaceship operator , it was borrowed from Perl. It is usually used for sorting because it returns -1 if the left operand is less than the right operand, 1 if the right operand is larger than the left and otherwise returns 0.

 1 <=> 2 # => -1 2 <=> 1 # => 1 1 <=> 1 # => 0 
+5
source

He called the spacecraft operator.

For basic numeric and string classes, this is a comparison operator that returns -1, 0, or 1.

In theory, a class can define any operator to do whatever it wants, but it will be the method that is used when sorting. It might make sense to define <=> for an arbitrary application class if this class ever needs to be ordered.

+1
source

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


All Articles