The each iterator method tutorial
Being able to cycle through a list of values is something that you'll be doing on a daily basis when working with Ruby programs. In this section, we are going to go through Ruby's popular iterator: the each
loop.
You already learned how to use while
loops. If you remember, there were a number of different rules for ensuring that our while
loops were processed a specific number of times. We also had to ensure that we didn't run into an infinite loop that would crash our program. It's for these reasons that while
loops aren't utilized in Ruby very often. Instead, the each
mechanism is the tool of choice when it comes to looping over collections.
The each loop code example
Before we can use the each
loop, we need to create a collection that it can work with. For simplicity's sake, and since we haven't gotten to our array, I'm going to use a very basic array of integers:
arr = [23, 2343, 454, 123, 345345, 1232]
Now that we have a collection to work with, we can...