What is the Ruby <=>
(spaceship) operator? Is the operator implemented by any other languages?
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.
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.
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.
In Ruby, the === operator is used to test equality within a when clause of a case statement.
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.
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>]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With