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

后端 未结 2 873
慢半拍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: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]
    

提交回复
热议问题