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

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

    When you use the sort method on a hash, you receive two element arrays in your comparison block, with which you can do comparisons in one pass.

    hsh = { 'the' => '6', 'we' => '6', 'those' => '5', 'have' => '3'}
    ary = hsh.sort do |a,b|
      # a and b are two element arrays in the format [key,value]
      value_comparison = a.last <=> b.last
      if value_comparison.zero?
        # compare keys if values are equal
        a.first <=> b.first
      else
        value_comparison
      end
    end
    # => [['have',3],['those',5],['the',6],['we',6]]
    

    Note that the result is an array of arrays because hashes do not have intrinsic order in ruby

提交回复
热议问题