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

后端 未结 3 534
梦毁少年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 08:50

    Use sort:

    total = {"Bob"=>37, "Alice"=>42, "Carl"=>42}
    total.sort { |(k1, v1), (k2, v2)| [v1, k2] <=> [v2, k1] }.to_h
    # => {"Bob"=>37, "Carl"=>42, "Alice"=>42}
    

    First, sort by values (v1 <=> v2) and then reverse sort by keys (k2 <=> k1), and since we need it simultaneously, put it into array.

    EDIT: @Mirror318, it just looks scary, take a look at the excellent explanation here: What is the Ruby <=> (spaceship) operator?

提交回复
热议问题