- Read Tutorial
- Watch Guide Video
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 lesson, we are going to go through Ruby's popular iterator, the each loop.
You've 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.
Each
Loop Code Example
Before we can use the each
loop we need to create a collection that it can work with. For simplicity sake, and since we haven't gotten to our Array
section, 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 implement an each
loop.
arr.each do |i| p i end
If you run this, you can see the values in the array printed out. Also notice that the each
tool gives us the ability to use a block variable. In this case the block variables is i
and we place it in between the pipes. This block variable will give us access to each value in the array as the loop iterates through the collection. For our example, with the first iteration i
will be set to 23
, the second time through it will be set to 2343
, and so on. This is a helpful tool because it allows us to work with each element in the collection. For example, if it was an array of strings that we wanted to capitalize we could loop through and have the code i.upcase
inside the block and all of the strings would be printed out as uppercase values.
In referencing what we've learned about blocks. You have have already guessed that we can also swap out our do...end
block for curly braces. So the same code could be written out this way as well:
arr.each { |i| p i }
If you run this code, you'll get the same result. However, make sure you follow the Ruby block rule of thumb where you only place the code on the same line if it's small and concise.
Now, I want to show you a real-world example of how to use the each
loop. This code is taken from a Ruby on Rails project that I built.
In this code, the jobs
instance variable stores a list of jobs. and during every iteration, that particular element of jobs
is stored in the block variable job
. I can do anything I want with the variable job
inside my code block. In this example I'm printing out different elements associated with a specific job.
So, that's how you use the Each loop in a real-life application.