How does the .each iterator work?


#1



https://www.codecademy.com/en/courses/ruby-beginner-en-F3loB/2/2?curriculum_id=5059f8619189a5000201fbcb


Why is it that when I put "kickinghorse" between the | | of the .each iterator, it puts out 6 repeates of the hash and when I put languages it only puts out one iteration?


Version A:
languages = ["HTML", "CSS", "JavaScript", "Python", "Ruby", "Java"]

languages.each { | **kickinghorse** | puts languages }

Version B:
languages = ["HTML", "CSS", "JavaScript", "Python", "Ruby", "Java"]

languages.each { | **languages** | puts languages }


#2

Hi it'a because you put puts languages instead of puts kickinghorse here

languages.each { | **kickinghorse** | puts languages }

here an example

names = ["fred", "gred"]

names.each { |name|  puts name}

#output
fred
gred

the word you pur between the | | is the one you should puts


#3

Basically this lesson is just a little confusing because it uses the word languages for both the array name, and as placeholder word for individual items. This is incorrect.

Placeholder

A placeholder is the word between the | |. It's any appropriate word you want, used as a stand-in for how you refer to each item inside your array. In this situation, the placeholder should be singular, not plural. Use a word like language, item, or x.

Version B

Here, your first placeholder matches your second placeholder, so the code understands it to refer to the items, not your array, even though you used the same word languages for both. If you change the placeholder to something more appropriate like this:

languages = ["HTML", "CSS", "JavaScript", "Python", "Ruby", "Java"]

languages.each { | item | puts item }

item is the placeholder referring to each item in your array. For each item it comes across, it prints out the string value of that item. Thus, since it finds 6 items, it prints each of their values. No repeats.

Version A

However, when your second placeholder incorrectly has the same name as your array, you get 6 repeats:

languages = ["HTML", "CSS", "JavaScript", "Python", "Ruby", "Java"]

languages.each { | language | puts languages }

This is because we have assigned language (or kickinghorse etc) as placeholder for the items inside the array, while languages now refers to the whole array iteself. Thus the code goes through each item (or language) inside the array, and then prints out the whole array (called languages) for each item there is.

Thus, it finds 6 items, and prints the whole array's contents 6 times.