Reputation: 3464
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
Upvotes: 44
Views: 44924
Reputation: 364
Old question, but here are 2 other solutions, which are close, but found it more obvious when reading :
h = {"a"=>1, "c"=>3, "b"=>2, "d"=>4}
hash.sort_by(&:last).reverse # => [["d", 4], ["c", 3], ["b", 2], ["a", 1]]
hash.sort { |a,b| b.last <=> a.last }
Call to_h if you really need a hash instead of an array of arrays :
hash.sort_by(&:last).reverse.to_h # => {"d"=>4, "c"=>3, "b"=>2, "a"=>1}
hash.sort { |a,b| b.last <=> a.last }.to_h
Upvotes: 1
Reputation: 4925
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]
Upvotes: 97