I am having a problem understanding how array.sort{ |x,y| block } works exactly, hence how to use it?
An example from Ruby documentation:
In:
a.sort {|x,y| y <=> x } #=> ["e", "d", "c", "b", "a"]
what is x and y?
x and y are the elements being compared by the sorting algorithm.
This is useful to define for custom classes which element should be before the other.
For basic data ( numbers, strings , date, etc ) the natural order is predefined, but for customer element ( ie Employee ) you define who goes before who in a comparison. This block give you the chance to define that.
and what happens at y<=>x?
There, they are comparing the elements in descending order ( those with "higher" value will go first ) rather than the natural order ( x<=>y )
The <=> method stands for "compareTo" and return 0 if the elements are equivalent, or < 0 if x goes before than y or > 0 if x goes after y