Reputation: 3496
I have a hash like this:
a = { 29 => 3, 14 => 6, 13 => 2, 32 => 10 }
I want to sort this hash based on the values there, namely: 3,6,2,10
I can do a.values.sort
but it returns an array of just the sorted values. I want to sort the actual hash, so it should return a new hash (or ideally update the original hash with the sorted one) with all the same key-value pairs but sorted!!
Upvotes: 3
Views: 251
Reputation: 80105
This works on Ruby 1.9:
a = { 29 => 3, 14 => 6, 13 => 2, 32 => 10 }
p Hash[a.sort_by{|k,v| v}]
#=> {13=>2, 29=>3, 14=>6, 32=>10}
Upvotes: 5
Reputation: 16861
A Hash in Ruby (pre-1.9) is unsorted. You can't 'return a new hash with the same key-value pairs sorted', because the Hash implementation simply does not keep the entries sorted. You have two options:
Upvotes: 2