Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Ruby <=> (spaceship) operator?

What is the Ruby <=> (spaceship) operator? Is the operator implemented by any other languages?

like image 790
Justin Ethier Avatar asked May 06 '09 01:05

Justin Ethier


People also ask

What is the point of the spaceship operator?

In PHP 7, a new feature, spaceship operator has been introduced. It is used to compare two expressions. It returns -1, 0 or 1 when first expression is respectively less than, equal to, or greater than second expression.

What does <=> do in Ruby?

It's a general comparison operator. It returns either a -1, 0, or +1 depending on whether its receiver is less than, equal to, or greater than its argument.

What is the operator in Ruby?

An operator is a symbol that represents an operation to be performed with one or more operand. Operators are the foundation of any programming language. Operators allow us to perform different kinds of operations on operands. There are different types of operators used in Ruby as follows: Arithmetic Operators.

What does === mean in Ruby?

In Ruby, the === operator is used to test equality within a when clause of a case statement.


2 Answers

It's also known as the Three-Way Comparison Operator. Perl was likely the first language to use it. Some other languages that support it are: Apache Groovy, PHP 7+, and C++20.

Instead of returning 1 (true) or 0 (false) depending on whether the arguments are equal or unequal, the spaceship operator will return 1, 0, or −1 depending on the value of the left argument relative to the right argument.

a <=> b :=   if a < b then return -1   if a = b then return  0   if a > b then return  1   if a and b are not comparable then return nil 

It's commonly used for sorting data.

like image 146
TonyArra Avatar answered Nov 12 '22 16:11

TonyArra


The spaceship method is useful when you define it in your own class and include the Comparable module. Your class then gets the >, < , >=, <=, ==, and between? methods for free.

class Card   include Comparable   attr_reader :value    def initialize(value)     @value = value   end    def <=> (other) #1 if self>other; 0 if self==other; -1 if self<other     self.value <=> other.value   end  end  a = Card.new(7) b = Card.new(10) c = Card.new(8)  puts a > b # false puts c.between?(a,b) # true  # Array#sort uses <=> : p [a,b,c].sort # [#<Card:0x0000000242d298 @value=7>, #<Card:0x0000000242d248 @value=8>, #<Card:0x0000000242d270 @value=10>] 
like image 21
steenslag Avatar answered Nov 12 '22 17:11

steenslag