How to sort a hash by value in descending order and output a hash in ruby?

41,205

Solution 1

Try:

Hash[h.sort.reverse]

This should return what you want.

Edit:

To do it by value:

Hash[h.sort_by{|k, v| v}.reverse]

Solution 2

Try this:

Hash[h.sort_by{ |_, v| -v }]
Share:
41,205
tipsywacky
Author by

tipsywacky

python for real...

Updated on July 09, 2022

Comments

  • tipsywacky
    tipsywacky almost 2 years
    output.sort_by {|k, v| v}.reverse
    

    and for keys

    h = {"a"=>1, "c"=>3, "b"=>2, "d"=>4}
    => {"a"=>1, "c"=>3, "b"=>2, "d"=>4}
    
    Hash[h.sort]
    

    Right now I have these two. But I'm trying to sort hash in descending order by value so that it will return

    => {"d"=>4, "c"=>3, "b"=>2, "a"=>1 }
    

    Thanks in advance.

    Edit: let me post the whole code.

    def count_words(str)
      output = Hash.new(0)
      sentence = str.gsub(/,/, "").gsub(/'/,"").gsub(/-/, "").downcase
      words = sentence.split()
      words.each do |item|
        output[item] += 1 
      end
      puts Hash[output.sort_by{ |_, v| -v }]
      return Hash[output.sort_by{|k, v| v}.reverse]
    end
    
    • Patrick Oscity
      Patrick Oscity over 11 years
      Remember that hashes do not have an order previous to Ruby 1.9
  • tipsywacky
    tipsywacky over 11 years
    but that sort the key thought, i'm trying to sort the value
  • tipsywacky
    tipsywacky over 11 years
    hmmm....i thought that's the way too. How come I see unless1sunday1or1on2of2due1the5is1day2saturday1rent1falls1fi‌​rst2month2a1.. All the keys and values stuck together in the irb.
  • Luke
    Luke over 11 years
    It comes out perfectly fine for me. Are you using something other than this test hash?
  • tipsywacky
    tipsywacky over 11 years
    nope... well, if that's the way to sort it. then it probably something else making it output the wrong hash. I'll double check. Thanks anyway.
  • PJP
    PJP over 11 years
    "How come I see unless1sunday1or1on2of2due1the5is1day2saturday1rent1falls1fi‌​rst2month2a1", what version of Ruby are you using?