On Nov 29, 2007 11:09 AM, Nathan V. [email protected] wrote:
Can not understand how the block after sort works! Need help. thanks.
h = { “a” => 20, “b” => 30, “c” => 10 }
puts h.sort #=> [[“a”, 20], [“b”, 30], [“c”, 10]]
puts h.sort {|a,b| a[0]<=>b[0]} # as above
puts h.sort {|a,b| a[1]<=>b[1]} #=> [[“c”, 10], [“a”, 20], [“b”, 30]]
As can be read in the documentation:
Converts hsh to a nested array of [ key, value ] arrays and sorts it,
using Array#sort.
This means that sort will convert the array to this (in some order):
[[“a”, 20], [“b”, 30], [“c”, 10]]
and then call array sort on it. Checking the documentation on
Array#sort:
Returns a new array created by sorting self. Comparisons for the sort
will be done using the <=> operator or using an optional code block.
The block implements a comparison between a and b, returning -1, 0, or
+1. See also Enumerable#sort_by.
a = [ “d”, “a”, “e”, “c”, “b” ]
a.sort #=> [“a”, “b”, “c”, “d”, “e”]
a.sort {|x,y| y <=> x } #=> [“e”, “d”, “c”, “b”, “a”]
What this means is that in the block form, whenever the sort algorithm
needs to compare two elements of the array, it will yield to the block
passing both elements (remember that each element is itself an array
of [key,value] generated by the hash) and expecting a -1, 0 or 1
result, depending on which one you consider to be less than the other
or if they are equal.
In the case of the hash example above:
h.sort {|a,b| a[0]<=>b[0]}
the block will receive, for example:
a = [“a”, 20]
b = [“b”, 30]
or
a = [“a”, 20]
b = [“c”, 10]
or whatever pairs the sorting algorithm needs to compare. Then inside
the block you need to provide the comparison of the two elements. The
first example is doing a comparison of the keys, because the first
element of the pair is the hash key, so:
a[0] <=> b[0]
calls the spaceship operator on the keys of the hash. While the second
one a[1] <=> b[1] compares the values of the hash.
Hope this makes any sense.
Jesus.