Skip to content

Instantly share code, notes, and snippets.

@ashleygwilliams
Created October 22, 2013 18:58
Show Gist options
  • Save ashleygwilliams/7106147 to your computer and use it in GitHub Desktop.
Save ashleygwilliams/7106147 to your computer and use it in GitHub Desktop.
walking through the each method in ruby

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:

STEP A

  1. words.each means lets get the first thing from words, which means the string "Pikachu"
  2. ... and take that thing and set it to the variable word
  3. so now word = "Pikachu"
  4. the variable word is now passed to the block (this is what the do |word| syntax means)

our block is simply the line puts word

  1. now we execute the block, aka puts word. since word = "Pikachu" we print Pikachu to the console

STEP B

  1. Repeat Step A with the next thing from words, in this case, "Bulbasaur"

STEP C

  1. Repeat Step A with the next thing from words, in this case, "Charmander"
@nixsticks
Copy link

I always pick Charmander

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment