In your example
a.sort
is equivalent to
a.sort { |x, y| x <=> y }
As you know, to sort an array, you need to be able to compare its elements (if you doubt that, just try to implement any sort algorithm without using any comparison, no <
, >
, <=
or >=
).
The block you provide is really a function which will be called by the sort
algorithm to compare two items. That is x
and y
will always be some elements of the input array chosen by the sort
algorithm during its execution.
The sort
algorithm will assume that this comparison function/block will meet the requirements for method <=>
:
- return -1 if x < y
- return 0 if x = y
- return 1 if x > y
Failure to provide an adequate comparison function/block will result in array whose order is undefined.
You should now understand why
a.sort { |x, y| x <=> y }
and
a.sort { |x, y| y <=> x }
return the same array in opposite orders.
To elaborate on what Tate Johnson added, if you implement the comparison function <=>
on any of your classes, you gain the following
- You may include the module
Comparable
in your class which will automatically define for you the following methods: between?
, ==
, >=
, <
, <=
and >
.
- Instances of your class can now be sorted using the default (ie without argument) invocation to
sort
.
Note that the <=>
method is already provided wherever it makes sense in ruby's standard library (Bignum
, Array
, File::Stat
, Fixnum
, String
, Time
, etc...).