bytebiscuit
bytebiscuit

Reputation: 3496

sort a hash by using the values of keys

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

Answers (2)

steenslag
steenslag

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

Confusion
Confusion

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:

  1. Use an instance of ActiveSupport::OrderedHash (from the active_support gem)
  2. Use an array of sorted pairs to perform any actions that require sorted input. Convert back to a Hash by passing that array to a Hash constructor (Hash.new or Hash[])

Upvotes: 2

Related Questions