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

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

    words = {'the' => 6,'we' => 7,'those' => 5,'have' => 3}
    sorted_words = words.sort { |a,b| b.last <=> a.last }
    sorted_words.each { |k,v| puts "#{k} #{v}"}
    

    produces:

    we 7
    the 6
    those 5
    have 3
    

    You probably want the values to be integers rather than strings for comparison purposes.

    EDIT

    Oops, overlooked the requirement that it needs to be sorted by the key too. So:

    words = {'the' => 6,'we' => 7,'those' => 5,'have' => 3,'zoo' => 3,'foo' => 3}
    sorted_words = words.sort do |a,b|
      a.last == b.last ? a.first <=> b.first : b.last <=> a.last
    end
    sorted_words.each { |k,v| puts "#{k} #{v}"}
    

    produces:

    we 7
    the 6
    those 5
    foo 3
    have 3
    zoo 3
    

提交回复
热议问题