Loops in Ruby - 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.

loop

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

each


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

for


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

while


It'll execute code block while condition is true

until


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

times


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

step


Passes each nth element to the block

upto


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

downto


Opposite of above method

break


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

next


Skips to the next iteration

redo


Restarts the current iteration

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

Summary


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 - unsplash.com