Velocity Reviews > Ruby > Sorting keys of hash based on value

# Sorting keys of hash based on value

Aldric Giacomoni
Guest
Posts: n/a

 03-22-2010
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
--
Posted via http://www.ruby-forum.com/.

Riccardo Cecolin
Guest
Posts: n/a

 03-22-2010
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
>

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]

Aldric Giacomoni
Guest
Posts: n/a

 03-22-2010
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/.

Rob Biedenharn
Guest
Posts: n/a

 03-22-2010
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] }

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
http://www.velocityreviews.com/forums/(E-Mail Removed)

Robert Klemme
Guest
Posts: n/a

 03-22-2010
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] }

Just for the variety:

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

Kind regards

robert

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