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.sortfruit.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.sortWith a block given, you are passed two of the sub-arrays into the block and you can do whatever sort of comparison on them.# => [["apples", 2], ["bananas", 3], ["oranges", 1]]
So to sort the original hash by values
fruit.sort {|a,b| a[1] <=> b[1]}or from higher values to lower values:# => [["oranges", 1], ["apples", 2], ["bananas", 3]]
fruit.sort {|a,b| b[1] <=> a[1]}# => [["bananas", 3], ["apples", 2], ["oranges", 1]]