5. Iterating over the array


I'm suddenly very confused here. Is 'words' an array? I thought that this was more like a method or function that separates the individual words. Why would the words of the input text be keys that have values? Where would these values com from exactly? This is the code I've come up with, but it's partly guesswork really. Please help.

puts "How are you today?"
text = gets.chomp
words = text.split
frequencies = Hash.new(0)
words.each = frequencies[words]
words += 1


Basically, what you are trying to do, is set up a system to count the occurrence of each and every single word.
The method .split separates the words in the string of text. So you get an array of strings
What you want to do after splitting the words, is count how often those words occur in the text. You would use the .each method for that. The .each method is a way of looping through every word in words.
So you won't need the = sign in that piece of code.
more like this: words.each {do |word| frequencies[words]}

It may actually be useful to browse through the chapter about loops.
I hope this helps!

Have a great weekend!


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