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:

···

--
Posted via http://www.ruby-forum.com/.

Aldric Giacomoni wrote:

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:
  

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!

···

--
Posted via http://www.ruby-forum.com/\.

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
Rob@AgileConsultingLLC.com

···

On Mar 22, 2010, at 2:40 PM, Aldric Giacomoni 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!

Just for the variety:

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

Kind regards

  robert

···

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

On Mar 22, 2010, at 2:40 PM, Aldric Giacomoni 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] }

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/