Sorting a hash by value then by key (but the key is reversed)

后端 未结 3 532
梦毁少年i
梦毁少年i 2021-01-15 08:28

The title says it all.

total = {\"Bob\"=>37, \"Alice\"=>42, \"Carl\"=>42}

I want to sort it by value, and then by key, but with th

3条回答
  •  时光说笑
    2021-01-15 09:03

    If you're using ruby >= 2.1, then just call to_h on sorted array of tuples:

    total = {"Bob"=>37, "Alice"=>42, "Carl"=>42}
    total.sort_by{|k, v| [v, k]}.to_h
    

    Else call Hash.new:

    total = {"Bob"=>37, "Alice"=>42, "Carl"=>42}
    Hash.new total.sort_by{|k, v| [v, k]}.to_h
    

提交回复
热议问题