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

Posted by tipsywacky on Stack Overflow See other posts from Stack Overflow or by tipsywacky
Published on 2012-11-04T04:30:06Z Indexed on 2012/11/04 5:00 UTC
Read the original article Hit count: 81

Filed under:
|
|
|
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)
  # YOUR CODE HERE
  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

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby