Sorting the hash


I could figure out the correct code. I just want help understanding how this code asks to do a word count. is it the word ‘count’ itself? how does this code let the program know that we want to see the frequency of each word? also im having trouble understanding the purpose of { |word| frequencies[word] += 1 }

puts "what did yu do last night:"
text = gets.chomp

words = text.split

frequencies =

words.each { |word| frequencies[word] += 1 }

frequencies = frequencies.sort_by do |word, count|



Your each method accepts a block to do something with each element, and your sort_by accepts a block to tell it what to sort by. As for seeing the result, you’d want to puts out the result at the end, perhaps some extra code to format it.


No, that word has no practical meaning other than to describe what the values are in the hash for each word key.

We must iterate over all the text to build up the hash with unique words. If your text phrase was longer, with more repeated words this would be evident.

frequencies =

The above invokes a new Hash instance with the directive to initialize each added key with the value of zero. We need that initial value so we can do math (addition). That’s where the next line comes in.

the rain in spain falls mainly in the plains

Split into an array,

['the', 'rain', 'in', 'spain', 'falls', 'mainly', 'in', 'the', 'plains']

The result of words.each will look like,

  'the' => 2,
  'rain' => 1,
  'in' => 2,
  'spain' => 1,
  'falls' => 1,
  'mainly' => 1,
  'plains' => 1
      ^       ^
    word    count


so im assuming the that this line
words.each { |word| frequencies[word] += 1 }

finds the frequency of each word?




Thank you, i understand now :slight_smile:


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.