How to sort a hash by value in descending order and output a hash in ruby? How to sort a hash by value in descending order and output a hash in ruby? ruby ruby

How to sort a hash by value in descending order and output a hash in ruby?


Try:

Hash[h.sort.reverse]

This should return what you want.

Edit:

To do it by value:

Hash[h.sort_by{|k, v| v}.reverse]


Try this:

Hash[h.sort_by{ |_, v| -v }]