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

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

    word_counts = {
            'the' => 6,
            'we' => 7,
            'those' => 5,
            'have' => 3,
            'and' => 6
    };
    
    word_counts_sorted = word_counts.sort do
            |a,b|
            # sort on last field descending, then first field ascending if necessary
            b.last <=> a.last || a.first <=> b.first
    end
    
    puts "Unsorted\n"
    word_counts.each do
            |word,count|
            puts word + " " + count.to_s
    end
    
    puts "\n"
    puts "Sorted\n"
    word_counts_sorted.each do
            |word,count|
            puts word + " " + count.to_s
    end
    

提交回复
热议问题