Let's do this with a simpler example:
Let's write a program that prints each word in an array to the console.
Here's our array words = ["Pikachu", "Bulbasaur", "Charmander"]
Here's our code:
words.each do |word|
puts word
end
So what's it do? Let's break it down:
words.each
means lets get the first thing from words, which means the string"Pikachu"
- ... and take that thing and set it to the variable
word
- so now
word
= "Pikachu" - the variable
word
is now passed to the block (this is what thedo |word|
syntax means)
our block is simply the line puts word
- now we execute the block, aka
puts word
. sinceword = "Pikachu"
we printPikachu
to the console
- Repeat Step A with the next thing from words, in this case, "Bulbasaur"
- Repeat Step A with the next thing from words, in this case, "Charmander"
I always pick Charmander