Iterating array elements into the hash, how does it know?


My code works fine, I just don't really understand what Ruby is thinking when processing commands, so I was hoping someone could explain it:

words = text.split(" ")

frequencies =

words.each do |word|
    frequencies[word] += 1

In this code, I have an array called "words." I then create an empty hash with a default value of 0. I then iterate over the "words" array, giving each item in that array the variable of "word" as it passes though the command. I then call the frequencies hash and assign a new key to it named whatever is held in the "word" variable. As a new key, it is automatically assigned the "frequency" hash's default value, which is 0, and then increases it by 1.

Here is my question: how does the program know what I mean by "frequencies[word]" is to use whatever is held in the "word" variable and not to assign the actual value "word"? And what if the iterated array contained the string "word," would it be impossible to refer to that key inside of an each function that uses a variable by the same name?


[]= is a method of hash which contains the code for exactly that behaviour, and somewhere there's code that in some way makes += use []=, or maybe it's a method of its own, don't really know

Point is, there's no thinking. Some particular operations have been defined and you can use those. To make those operations fit together into something meaningful, it takes a programmer to do the thinking (whatever that means)


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