Sort a hash using key values

I have a hash like this:

a = { 29 => 3, 14 => 6, 13 => 2, 32 => 10 }

I want to sort a hash based on values, namely: 3,6,2,10

I can do a.values.sort

but it returns an array of only 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 !!

+3
source share
2 answers

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}
+5
source

A Hash in Ruby (prior to 1.9) is not sorted. You cannot "return a new hash with the same key-value pairs" because the Hash implementation simply does not sort the entries. You have two options:

  • ActiveSupport:: OrderedHash ( active_support)
  • , . Hash, Hash (Hash.new Hash [])
+2

All Articles