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 }]
Comments
-
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 over 11 yearsRemember that hashes do not have an order previous to Ruby 1.9
-
-
tipsywacky over 11 yearsbut that sort the key thought, i'm trying to sort the value
-
tipsywacky over 11 yearshmmm....i thought that's the way too. How come I see unless1sunday1or1on2of2due1the5is1day2saturday1rent1falls1first2month2a1.. All the keys and values stuck together in the irb.
-
Luke over 11 yearsIt comes out perfectly fine for me. Are you using something other than this test hash?
-
tipsywacky over 11 yearsnope... 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 over 11 years"How come I see unless1sunday1or1on2of2due1the5is1day2saturday1rent1falls1first2month2a1", what version of Ruby are you using?