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
is equivalent to
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
sortalgorithm to compare two items. That isxandywill always be some elements of the input array chosen by thesortalgorithm during its execution.The
sortalgorithm 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
and
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 followingComparablein 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…).