Project Ramon

A learning journey from a Ruby noob perspective

Control Flow II: Iterator methods in Ruby


In Ruby, iterators are methods supported by Arrays and Hashes. These two classes are Ruby’s tools for dealing with collections, and iterators return elements within a collection, one-by-one. There are two main methods to return elements out of an array or hash.

Method .each

The .each method can be called when you want to list your collections one element at a time.
Lets first confirm that we can actually use the .each method on an array. We can do something like so for confirmation:


We have confirmed that .each is an available method in this Array object with the first line. We can also generate a complete list of methods available by just appending the .methods method to the object in question. That is the line starting with [4] pry(main)> in the illustration above.

Lets see a quick demonstration of how we could use the .each method in practice:

Above we assigned an array to the color_list variable. The array contains seven elements initially, and we iterate over the array using the .each method to select all of the elements larger than 4 letters and place them inside of a different array called big_colors.

If we wanted to iterate over the array’s index instead of it’s elements, we could utilize the .each_index method like so:


The .each_index does exactly the same thing as the .each method does, except that instead of listing the elements contained inside the array, it lists the indexes.

Method .collect

The methods .collect and .map (which are synonymous) creates a new array containing the values returned to it by the block.

Here is an example:


Using .collect or .collect! we can temporarily or permanently modify the elements in our array with statements written inside a code block.


Categories: AirPair, Newbie, Ruby

Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s