What is the Ruby <=>
(spaceship) operator? Is the operator implemented by any other languages?
相关问题
- How to specify memcache server to Rack::Session::M
- Why am I getting a “C compiler cannot create execu
- reference to a method?
- ruby 1.9 wrong file encoding on windows
- gem cleanup shows error: Unable to uninstall bundl
相关文章
- Ruby using wrong version of openssl
- What does it means in C# : using -= operator by ev
- Difference between Thread#run and Thread#wakeup?
- how to call a active record named scope with a str
- C# generics class operators not working
- “No explicit conversion of Symbol into String” for
- Segmentation fault with ruby 2.0.0p247 leading to
- How to detect if an element exists in Watir
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.
Since this operator reduces comparisons to an integer expression, it provides the most general purpose way to sort ascending or descending based on multiple columns/attributes.
For example, if I have an array of objects I can do things like this:
This basic pattern can be generalized to sort by any number of columns, in any permutation of ascending/descending on each.
According to the RFC that introduced the operator, $a
<=>
$bExample:
MORE:
Perl was likely the first language to use it. Groovy is another language that supports it. Basically instead of returning
1
(true
) or0
(false
) depending on whether the arguments are equal or unequal, the spaceship operator will return1
,0
, or−1
depending on the value of the left argument relative to the right argument.It's useful for sorting an array.
I will explain with simple example
[1,3,2] <=> [2,2,2]
Ruby will start comparing each element of both array from left hand side.
1
for left array is smaller than2
of right array. Hence left array is smaller than right array. Output will be-1
.[2,3,2] <=> [2,2,2]
As above it will first compare first element which are equal then it will compare second element, in this case second element of left array is greater hence output is
1
.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.