RubyGuides
Share this post!

The Definitive Guide to Loops in Ruby

In this article you will learn many different ways to write a Ruby loop.

A loop lets you repeat some action a number of times.

You can also go over a list of things, like an array or a hash, and work with each individual element.

If you are a beginner I don’t want you to get overwhelmed by all the options. So stick with the each & times methods described here.

For my more advanced readers this will help you review & expand your toolbox of looping methods.

The Each Loop

This loop requires you to have a collection of items, like an array, a range or a hash to be able to use it.

Example:

This will print all the numbers inside the numbers array [1,3,5,7].

Notice how we have this syntax with the |n|.

In case you are not familiar with this, we call the whole thing after each a block { |n| puts n }.

A block is just a way to create a method without a name.

So what happens is that each, or any other method that takes a block, is able to use our name-less method.

And that’s how puts n is run multiple times.

If you want to use each with a hash you will need two parameters (one for the key & another for the value).

Example:

Give this a try 🙂

Each With Index

There are some cases where you want to use each but you need the index number.

You can use the each_with_index method:

The Times Loop

This is possibly the easiest loop you can come up with.

Look at this code:

This will print the word "hello" 10 times.

As you can see there isn’t much to it & it should be easy to remember.

But what if you want the number?

In the last example, with the each loop, we had access to this n so we could print it.

You can also do that with times.

Example:

This will print hello 0, hello 1, hello 2, etc.

Give it a try!

The key here is the little |i| thing, which by the way, can be anything. It doesn’t have to be an |i|. It could be |n| or |foo|, or |bacon|

It’s just a name!

If you are familiar with methods, this |n| is like a method parameter. In other words, it’s just a variable that becomes the current value for each iteration of our times loop.

Range Looping

You may have noticed that when using the times method it starts counting from 0.

This can be a bit inconvenient if you want to start with a different number.

You can use a range & the each method to have more control over the starting & ending numbers.

Example:

This will print all numbers from 1 to 10.

Ruby While Loop

The while loop is available in most programming languages so it’s always useful to know. It’s also the kind of loop that you can fall-back to when everything else fails.

And there are some situations when only a while loop would make sense. For example, if you don’t know how many times you need to loop in advance.

Here’s a code example:

This will print all the numbers from 0 to 9 (10 excluded).

Notice that there are some important components:

  • The n variable
  • The condition (n < 10)
  • The n += 1

All of these components are critical for this to work.

The variable n holds the value we are using for counting, the condition (n < 10) tells Ruby when to stop this loop (when the value of n is greater or equal to 10), and the n += 1 advances the counter to make progress.

Skipping Iterations

In all of these loop types you can skip iterations.

Let’s say that you are going over an array of numbers & you want to skip odd numbers.

You could do something like this:

The key here is the next keyword, which skips to the next loop iteration (the next number in this case).

A better way to do this is to use other methods like step & select.

Example:

Stopping Early

You can also break out of a loop early, before the condition is met, or before you go over all the elements of the collection.

The following example stops when it finds a number higher than 10:

The key here is the break keyword.

The Kernel#loop Method

The last kind of loop we are going to talk about is literally the loop method.

This method takes a block & it runs an infinite number of times.

Example:

You can stop a loop method in two ways:

  • Raising a StopIteration exception
  • Using the break keyword

Summary

You have learned many different ways to loop in Ruby! Including the times method, the each method, the loop method & the while keyword.

You have also learned how to control the loops by skipping iterations with next & breaking out of loops with break.

Leave a Comment:

2 comments
Phil says last month

Just an FYI, the code in Skipping Iterations prints the even iterations it doesn’t skip them.

Reply
    Jesus Castello says last month

    You are right Phil! Thanks for letting me know, it should be fixed 🙂

    Reply
Add Your Reply