Sorting keys of hash based on value

Let’s say we have this contrived example:

hash = {:a => {:happy => 5},
:b => {:happy => 4},
:c => {:happy => 7}
}

I would like to get the keys sorted by descending :happy value, like so:

[:c, :a, :b]

How would I do this?
The best I’ve come up with is this:

irb(main):018:0> hash.sort_by { |x, y| -y[:happy] }
=> [[:c, {:happy=>7}], [:a, {:happy=>5}], [:b, {:happy=>4}]]

It’s not elegant :frowning:

Aldric G. wrote:

How would I do this?
The best I’ve come up with is this:

irb(main):018:0> hash.sort_by { |x, y| -y[:happy] }
=> [[:c, {:happy=>7}], [:a, {:happy=>5}], [:b, {:happy=>4}]]

It’s not elegant :frowning:

Do you want keys or the whole hash?

irb(main):015:0> hash.keys.sort { |a,b| hash[b][:happy] <=>
hash[a][:happy] }
=> [:c, :a, :b]

Riccardo Cecolin wrote:

Do you want keys or the whole hash?

irb(main):015:0> hash.keys.sort { |a,b| hash[b][:happy] <=>
hash[a][:happy] }
=> [:c, :a, :b]

Of course… I was trying to make it too complicated. Thanks!

On 03/22/2010 08:49 PM, Rob B. wrote:

Or the slightly simpler sort_by

hash.keys.sort_by {|k| hast[k][:happy] }

Just for the variety:

hash.sort_by {|k,v| -v[:happy]}.map(&:first)

Kind regards

robert

On Mar 22, 2010, at 2:40 PM, Aldric G. wrote:

Riccardo Cecolin wrote:

Do you want keys or the whole hash?

irb(main):015:0> hash.keys.sort { |a,b| hash[b][:happy] <=>
hash[a][:happy] }
=> [:c, :a, :b]

Of course… I was trying to make it too complicated. Thanks!

Or the slightly simpler sort_by

hash.keys.sort_by {|k| hast[k][:happy] }

If the hash.size is large, this can be a big performance win, but with
just three keys, you won’t notice any difference.

-Rob

Rob B. http://agileconsultingllc.com
[email protected]