开发者

Sorting a 2-D hash in reverse order

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}}
开发者_StackOverflow中文版

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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜