0

When I use sort_by on the frequency hash, it returns an array. How do I return a hash instead?

puts frequency.class        #returns hash
frequency = frequency.sort_by {|k,v| v}.reverse
puts frequency.class        #returns array
0

2 Answers 2

1

sort_by just returns an array. You can cast it back to a hash like this:

frequency = frequency.sort_by {|k,v| v}.reverse
frequency = Hash[frequency]
Sign up to request clarification or add additional context in comments.

7 Comments

I don't think I'd call that casting, but yeah, this is the solution.
This doesn't work for me in 1.9.3. The hash 'order' (via each) changes, but it's not sorted.
@JimStewart That approach works fine for me under ruby 1.9.3. I tried this code for instance: h = {:fernando => 28,:john => 18,:peter => 54} Hash[h.sort_by { |name, age| age }.reverse]
That's the correct result. See the .reverse at the end. It would give you the values order by age starting by the oldest onto the youngest.
For me it works in both 1.9.3 and 2.0.0. @JimStewart, you are talking about keys, but asker seems to want to sort on values. Which is what fmendez' example does too: a reverse sort on age.
|
1

This is a pretty old question, but using Ruby 2.2+ it's pretty simple:

frequency.sort_by { |_, v| -v }.to_h

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.