Home > Articles > Programming > Ruby

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Iterating over an Array

This is one of the joys of Ruby. It’s so easy!

You can also do the trusty old for loop:

for element in [1, 2, 3, 4, 5]
    # do something to element

The difference between a for loop and an #each is that in for, a new lexical scoping is not created. That is, any variables that are created by for or that are in the loop remain after the loop ends.

To traverse the Array in reverse, you can simply use #Arrayreverse#each. Note that in this case, a copy of the Array is being made by #reverse, and then #each is called on that copy. If your Array is very large, this could be a problem.

In order for you get any more specialized than that, however, you need to work with the Enumerator module. For example, you might want to traverse an Array processing five elements at a time as opposed to the one element yielded by #each:

require 'enumerator'
ary = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
ary.each_slice(5) { |element| p element }


[0, 1, 2, 3, 4]
[5, 6, 7, 8, 9]
  • + Share This
  • 🔖 Save To Your Account