From: Stefano Crocco Date: 2007-11-29T19:29:44+09:00 Subject: Re: Hash Sorting Alle giovedì 29 novembre 2007, Nathan Viswa ha scritto: > 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]] What Hash#sort does is: * first: convert the hash into a nested array: [['a', 20], ['b', 30], ['c', 10]] * second: sort that array according to the block. In the first call to sort, you don't pass a block to it, so the sorting will be performed by calling the <=> of the contents of the array (i.e, on the key - value arrays). Array#<=> compares the contents of the two arrays in order, returning +1 or -1 as soon as one of the items is different from the other. For example, ['a', 20]<=>['c', 10] returns -1 because 'a' precedes 'c'. If two entries had the same first element (here this is impossible since they come from a hash), the second element would be compared, an so on. Your second call to send gives the same result, because you're explicitly telling sort to compare only the first element of the array. As explained above, even in the blockless case sort never needs to check the second element, so the results are the same. In the third case, you tell sort to compare the second element of each pair (i.e, the value in the original hash). This way, the pair ['c', 10] becomes the first, because 10 is the lesser of the three values; ['a', 20] is the second because 20 is the middle value and ['b', 30] is the last because 30 is the greater value. I hope this helps Stefano