Learning Ruby

How to sort a hash

Hash.sort converts the hash to an array.
The hash's each key and value become the array element [key, value]

fruit = { "bananas" => 3, "oranges" => 1, "apples" => 2 }
fruit.sort
fruit.sort will internally create the array
[ ["bananas", 3], ["oranges", 1], ["apples", 2] ]
and then sort it using Array#sort.
Meaning when comparing the sub-arrays each element of the subarray is looked at.
fruit.sort 
# => [["apples", 2], ["bananas", 3], ["oranges", 1]]
With a block given, you are passed two of the sub-arrays into the block and you can do whatever sort of comparison on them.
So to sort the original hash by values
fruit.sort {|a,b| a[1] <=> b[1]} 
# => [["oranges", 1], ["apples", 2], ["bananas", 3]]
or from higher values to lower values:
fruit.sort {|a,b| b[1] <=> a[1]} 
# => [["bananas", 3], ["apples", 2], ["oranges", 1]]

 

 

January 05, 2010 at 2:57 am