1. Home
  2. Computing & Technology
  3. Perl

Using each - Beginning Ruby Tutorial, Control Structures
Looping through an array in Ruby with the each method

by Kirk Brown
for About.com

Next: Looping through a hash in Ruby with the each method

Every string, array, and hash in Ruby is an object, and every object of these types has a set of built in methods. Let's take a simple array of names, and see what we can do with the each method. First we create an array object by assigning the array to stooges

>> stooges = ['Larry', 'Curly', 'Moe']
Next we'll call the each method and create a small block of code to process the results.
>> stooges.each { |stooge| print stooge + "\n" }
This will produce the following output:
Larry
Curly
Moe
The each method takes two arguments - an element and a block. The element, contained within the pipes, is like a placeholder. Whatever you put in the pipes will be used in the block to represent each element of the array in turn. The block is the line of code that is executed on each of the array items, and is handed the element to process.

You can easily extend the code block to multiple lines by using do to define a larger block:

>> stuff.each do |thing|
.. print thing
.. print "\n"
.. end
This is exactly the same as the first example, except that the block is defined as everything after the element (in pipes) and before the end statement.

Next: Looping through a hash in Ruby with the each method

Explore Perl
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Perl
  4. Similar Languages
  5. Ruby each method tutorial - Control structures in Ruby, learn how to loop through an array or hash with each.>

©2009 About.com, a part of The New York Times Company.

All rights reserved.