method

sort

Importance_2
v1_8_7_72 - Show latest stable - 1 note - Class: Hash
sort() public

Converts hsh to a nested array of [ key, value ] arrays and sorts it, using Array#sort.

   h = { "a" => 20, "b" => 30, "c" => 10  }
   h.sort                       #=> [["a", 20], ["b", 30], ["c", 10]]
   h.sort {|a,b| a[1]<=>b[1]}   #=> [["c", 10], ["a", 20], ["b", 30]]
Show source
Register or log in to add new notes.
March 31, 2009
3 thanks

Sorting Hashes with Symbol Keys

To sort a hash with symbol keys, use Enumerable#sort_by:

h = { :a => 20, :b => 30, :c => 10  }
h.sort                       # => NoMethodError: undefined method `<=>' for :a:Symbol
h.sort_by { |k,v| k.to_s }   # => [[:a, 20], [:b, 30], [:c, 10]]