Sorting Ruby hash by value and stored the result in hash

Hi

I have problem in storing the sorted hash result in hash again.
for example

hash = {:a => 10, :b => 5, :c => 20, :d => 15 }

I have applied sorting as below using sort_by

hash.sort_by{|key,value| value } => [[:b, 5], [:a, 10], [:d, 15], [:c,
20]]

So here values are sorted but result is in array format.

How to build hash from this array as below? i.e sorting by value ?

{:b => 5, :a => 10, :d => 15, :c => 20}

Thanks in advance

···

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

Hashes are not sorted. (In 1.9.1, there's just the side effect of the
order of keys not changing randomly.)

To convert an array like the one returned by Hash#sort_by back to
hash, use Hash[ arr ].

You may also try googling "ordered hash ruby", there are some
solutions. But it may be simpler to refactor your code, so it doesn'/t
need to order a hash anymore, or use two objects: regular hash +
sorted array of its keys.

-- Matma Rex

···

2011/8/19 kevin peter <sateesh.mca09@gmail.com>:

Hi

I have problem in storing the sorted hash result in hash again.
for example

hash = {:a => 10, :b => 5, :c => 20, :d => 15 }

I have applied sorting as below using sort_by

hash.sort_by{|key,value| value } => [[:b, 5], [:a, 10], [:d, 15], [:c,
20]]

So here values are sorted but result is in array format.

How to build hash from this array as below? i.e sorting by value ?

{:b => 5, :a => 10, :d => 15, :c => 20}

Thanks in advance

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

just an idea: After the sort_by, you could just take the ordered keys for you "sorted" hash access.

regards
ralf

···

On 08/19/2011 09:14 AM, Bartosz Dziewoński wrote:

Hashes are not sorted. (In 1.9.1, there's just the side effect of the
order of keys not changing randomly.)

To convert an array like the one returned by Hash#sort_by back to
hash, use Hash[ arr ].

You may also try googling "ordered hash ruby", there are some
solutions. But it may be simpler to refactor your code, so it doesn'/t
need to order a hash anymore, or use two objects: regular hash +
sorted array of its keys.