Sorting a hash in Ruby by its value first then its key

后端 未结 7 748
轻奢々
轻奢々 2021-01-01 08:15

I am trying to sort a document based on the number of times the word appears then alphabetically by the words so when it is outputted it will look something like this.

相关标签:
7条回答
  • 2021-01-01 08:42

    Try this:

    words = {'the' => 6,'we' => 7,'those' => 5,'have' => 3}
    
    words.sort { |(x_k, x_v), (y_k, y_v)| [y_v, y_k] <=> [x_v, x_k]}
    #=> [["we", 7], ["the", 6], ["those", 5], ["have", 3]]
    
    0 讨论(0)
提交回复
热议问题