sharataka
sharataka

Reputation: 5132

How to return a hash after using sort_by in ruby?

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

Upvotes: 0

Views: 538

Answers (2)

Shannon Scott Schupbach
Shannon Scott Schupbach

Reputation: 1278

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

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

Upvotes: 1

Mischa
Mischa

Reputation: 43298

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]

Upvotes: 1

Related Questions