I have a hash in Ruby that is storing the word frequency of a string, with the word as the key and the frequency as the value.
words = a_string.split(/ /)
freqs = Hash.new(0)
words.each { |word| freqs[word] += 1 }
freqs = freqs.sort_by {|x,y| y }
freqs.reverse!
freqs.each do |word, freq|
puts word+' '+freq.to_s
end
I've read that hash iterators return the hash in a random order, but this seems to work so far.
Now I need to freqs hash to only contain the 20 most frequent words. How can I do this? Thanks for reading.