words = text.split (" ")
frequencies = Hash.new(0)
words.each { |x|
x = frequencies[x] += 1
}
words = text.split: This line splits the inputted text at the spaces. I get that.
frequencies: creates a new hash with default value of 0 for any key. Got it.
words.each: This is my problematic part. I’m confused about my variable.
Question 1: The x IS a variable, right?
Question 2: Are these lines saying “Assign each word from variable words to x. Then take x, which is each word, and assign it to a key in the hash named frequencies and add 1 to it’s default value.”
I hope I explained my questions clearly. If not please let me know and I’ll try to clarify. Thanks.
In words.each, the variable words. is an array object, with a class method, each that permits iteration of the array, one element at a time. x is the block parameter, a variable, yes.
Think in terms of a for..in loop,
for key in object
where key is the x in your block. We do not manually assign values to this variable as it is an internally managed object. So,
words.each { |x| frequencies[x] += 1 }
Essentially, yes. If the key does not exist, it is created with a default value of 0, then accumulated by 1. If it does exist, that key continues to accumulate.
know to group identical words together, and add 1 every time it encounters an identical word?
For example, “=” is used to assign things to variables, “gets” is used to get input from the user. I understand that each of these has a defined function. I don’t understand how simply putting “frequencies|x| += 1” tells it to assign each word to a key, to group identical words, and to add 1 to the default value for each identical word. If my words array was [cat, cat, dog, dog, dog, mouse], why wouldn’t the frequencies hash be:
cat 1
cat 1
dog 1
dog 1
dog 1
mouse 1
?
Thank you!
When a new word is found, a new key is created in the hash, given a default value of 0, then increased by 1. If a key already exists, it will be found, rather than created, and its value increased by 1.