tags:

views:

110

answers:

2

I have a 2-d hash.I need to sort each sub-hash by value in descending order.

hsh={"a"=>{0=>1, 1=>2}}

output= {"a"=>{1=>2,0=>1}}

Thanks & Cheers !

+2  A: 

You can't affect in what order the elements of a hashmap are iterated or displayed (Well in ruby 1.9 iteration (and display) order is guaranteed to be the same as insertion order, so if you create hash from a sorted array, the hash will be sorted as well).

All you can do is turn the hash into an array and sort that. Like:

hsh.map {|k,v| [k, v.sort.reverse]}
#=> [["a", [[1, 2], [0, 1]]]]
sepp2k
In Ruby 1.9, you can sort a hash with `Hash[h.sort]`.
Marc-André Lafortune
@Marc-AndreLafortune: Right. Good point.
sepp2k
A: 

Hash is UNORDERED collection. You can't set your own order.

http://apidock.com/ruby/Hash

The order in which you traverse a hash by either key or value may seem arbitrary, and will generally not be in the insertion order.

fl00r
Hashes are ordered in Ruby 1.9
Marc-André Lafortune
Cool, that's new for me
fl00r