Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 
like image 696
tipsywacky Avatar asked Nov 04 '12 04:11

tipsywacky


2 Answers

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] 
like image 134
Luke Avatar answered Sep 21 '22 06:09

Luke


Try this:

Hash[h.sort_by{ |_, v| -v }] 
like image 21
Jeweller Avatar answered Sep 23 '22 06:09

Jeweller