5. Iterating Over The Array. Can someone explain the .each variable?

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<Below this line, add a link to the EXACT exercise that you are stuck at.>
https://www.codecademy.com/en/courses/ruby-beginner-en-693PD/0/5?curriculum_id=5059f8619189a5000201fbcb
<In what way does your code behave incorrectly? Include ALL error messages.>
My code doesn’t behave incorrectly. I’d just like some clarification with the following piece of code:


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.

How does the following command

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

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!

By not grouping. It simply runs a count on a word, which word is the hash key.

How does it know to display each word once? Or is that something built into that code?

Going back to the animals example, why is the output
cat 2
dog 3
mouse 1

Rather than
cat 1
cat 1
dog 1
dog 1
dog 1
mouse 1
?

Thanks!

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.

2 Likes