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
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]
Try this:
Hash[h.sort_by{ |_, v| -v }]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With