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

后端 未结 2 872
慢半拍i
慢半拍i 2021-01-30 16:45
output.sort_by {|k, v| v}.reverse

and for keys

h = {\"a\"=>1, \"c\"=>3, \"b\"=>2, \"d\"=>4}
=> {\"a\"=>1, \"c\"=>3         


        
相关标签:
2条回答
  • 2021-01-30 17:16

    Try this:

    Hash[h.sort_by{ |_, v| -v }]
    
    0 讨论(0)
  • 2021-01-30 17:39

    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]
    
    0 讨论(0)
提交回复
热议问题