Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort a hash by using the values of keys

Tags:

ruby

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!!

like image 590
bytebiscuit Avatar asked Nov 26 '25 06:11

bytebiscuit


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}
like image 71
steenslag Avatar answered Nov 28 '25 02:11

steenslag


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[])
like image 24
Confusion Avatar answered Nov 28 '25 02:11

Confusion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!