Sorting keys of hash based on value

A

Aldric Giacomoni

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 :(
 
R

Riccardo Cecolin

Aldric said:
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 :(
Do you want keys or the whole hash?

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

Aldric Giacomoni

Riccardo said:
Do you want keys or the whole hash?

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


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

Rob Biedenharn

Riccardo said:
Do you want keys or the whole hash?

irb(main):015:0> hash.keys.sort { |a,b| hash[: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 Biedenharn http://agileconsultingllc.com
(e-mail address removed)
 
R

Robert Klemme

Riccardo said:
Do you want keys or the whole hash?

irb(main):015:0> hash.keys.sort { |a,b| hash[: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] }


Just for the variety:

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

Kind regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top