Site icon Treehouse Blog

How to Use the “each” Method in Ruby on Rails | Treehouse Quick Tip

The “each” method in Ruby on Rails allows you to iterate over different objects inside an array-like structure. It’s an important part of development in Ruby, and Treehouse’s Ruby teacher, Jason, explains how to use it effectively in this Treehouse Quick Tip!

Video Transcription

Jason: Hi. I’m Jason. In this Tree House quick tip, we’re going to
talk about the Each Method in Ruby. The Each Method is part of
the innumerable mix-in. The Each Method lets you iterate over
different objects inside of an array-like structure. The method
takes a block which specifies what will happen on each
successive iteration in the loop.

Here’s how the Each Method looks. Right now, I’m in an IRB
secession. Let me just create an array of a few different
things. I have an array with 3 different items in it right now:
Dog, cat and frog. If I wanted to go through and print out each
of the different items in the array, it’d be really easy to do
using the Each Method. Here’s what it would look like.

In order to call the Each Method, first, I type out the name of
the object I want to iterate over, which in this case is the
array variable. Then I type a ‘.’ which calls a method, and then
the name of the method that I want to call, in this case,
‘each’. From there, type out a space in the word ‘do’. ‘Do’
tells the Ruby interpreter that we’re going to expect a block.
Then I type another space, and I put the word |item|. Anything
in between || is an argument to the block, which was specified
by the ‘do’ keyword, and these arguments are going to be
available inside of the block. From there, I press ENTER and I
type out what I want to happen to the item. In this case, I’m
only printing out what the item is. You don’t need to worry
about modifying the original items inside the block, because
only a copy is sent in, and anything that you do won’t affect
the original item in the array.

That was one quick use of the Each Method, you can have as much
code as you want inside of the block, just make sure to keep it

Announcer: If you’d like to see more advanced videos and tutorials like
this one, go to, and start learning for free.

Exit mobile version