Iterating Over the Array


#1

why "word" in this case is known to the compiler. I define an array of "words" but in this case, "word"?
puts "Input your text"
text = gets.chomp
words = text.split
frequencies = Hash.new(0)
words.each { |word| frequencies[word]+=1}


#2

It is an arbitrary iterator variable. We could write any name, x, thor, hairy_thunderer.

In the block, |word| is an iterator variable of the each loop.

This line repairs another error in the OP:

words = text.split(" ")

We create an array of words extracted from the text by splitting at spaces between words in the string.


#3

But split uses whitespaces by default right?


#4

To answer your question, I would never make that assumption or assert as much. We should only assume that the method expects us to provide parameters, be it an empty string (split on letters and spaces, regardless) or a character, such as a space which is convenient since it separates words. We can split any string at the point where any character is found.

To repeat, it is not a safe assumption that a method has a built in default. Supply the parameter, and it doesn't come into question later.