Ruby Loops: Syntax For All Possible Approaches

Ruby comes with many statements and methods designed for looping. This amount can astonish both fledgling coders and developers experienced in other programming languages. In this post you'll be introduced to all ways of creating a loop in Ruby.

The list of Ruby loops


This is the simplest technique of creating a loop:

"I'm in loop" will be output infinitely. To prevent it, we can use the break statement


All classes that include enumerable module have to define an each method. In case of Array class, it calls the given block one time for every single element


The for loop in Ruby is just syntax sugar for the each method. Output of this code will be same as above

Keep in mind that the iterator variable still lives after the for loop is finished

Ruby does not allow to access the block's parameter outside it, so code like this:

Raises the exception, if i variable is not defined anywhere else

undefined local variable or method `i' for main:Object (NameError)

Most of Rubyists avoid the for loop because the visibility of the iterator variable outside the loop is confusing in more complicated programs


It'll execute code block while condition is true


This loop is similar to the while loop, except that, it works while condition is false

In while/until statements do keyword is optional, so feel free to skip it

You can think about while/until loops as a repeating if/unless statements


Handy method if you know exactly how many times to execute a block


Passes each nth element to the block


Passes to block each number, starting from number on which we call this method, up to limit defined in argument


Opposite of above method


Already introduced in this post. Helpful in preventing creation of infinite loops or finishing them before condition


Skips to the next iteration


Restarts the current iteration

It doesn't check loop condition, so it's easy to create infinite loop


As you can see loops in Ruby works slightly different than in other programming languages. Above examples seems quite simple, however, what's going under the hood confuses many newcomers. To gain a real understanding you must know how to work with blocks and understand object-orientation of this language.

credits: photo by -

Start a project with your dedicated software house



We do not track you online. We use only session cookies and anonymous identifiers for the purposes specified in the cookie policy. No third-party trackers.

I understand
Elo Mordo!Elo Mordo!