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

后端 未结 7 792
轻奢々
轻奢々 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:18

    Try this:

    Assuming:

    a = { 
      'the' => '6', 
      'we' => '7', 
      'those' => '5', 
      'have' => '3', 
      'hav' => '3', 
      'haven' => '3'
    }
    

    then after doing this:

    b = a.sort_by { |x, y| [ -Integer(y), x ] }
    

    b will look like this:

    [
      ["we", "7"], 
      ["the", "6"], 
      ["those", "5"], 
      ["hav", "3"], 
      ["have", "3"], 
      ["haven", "3"]
    ]
    

    Edited to sort by reverse frequencies.

提交回复
热议问题