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 !
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 !
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]]]]
Hash is UNORDERED collection. You can't set your own order.
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.