I am having a problem understanding how array.sort{ |x,y| block }
works exactly, hence how to use it?
An example from Ruby documentation:
a = [ "d", "a", "e", "c", "b" ]
a.sort #=> ["a", "b", "c", "d", "e"]
a.sort { |x,y| y <=> x } #=> ["e", "d", "c", "b", "a"]
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 <=>
:
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
Comparable
in your class which will automatically define for you the following methods: between?
, ==
, >=
, <
, <=
and >
.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...).