Don't understand why code counts words



I can’t seem to understand why this line of code

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

helps to count each time the input words appear.

My understanding is that every word regardless of repeats would be given a position on the array and not be aggregated.

Thank you.


That doesn’t pay attention to positions in the array, and if you mean frequencies, that’s a hash, not an array

You seem to describe this:

frequencies = []
words.each { |word| frequencies.push word }


Yes I meant a hash. I don’t understand why the words are being counted. Which exact line of code checks if the word is repeated and increases the count by 1. Thank you.

puts "Enter a phrase you’d like to analyze: "
text = gets.chomp

words = text.split

frequencies =

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

frequencies = frequencies.sort_by do |word, count|


frequencies.each do |word, count|
puts "#{word} #{count.to_s}"


Nothing checks if it’s repeated. It adds 1 regardless


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