Don't understand why code counts words


#1

Hi,

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.


#2

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 }

#3

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 = Hash.new(0)

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

frequencies = frequencies.sort_by do |word, count|
count
end

frequencies.reverse!

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


#4

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


#5

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