Source: unsplash.com

In the following article, we’re going to explore the following topics:

redo for loops & enumerations

for loops & enumerations redo and blocks

Before to start

I’m thrilled to share with you our latest project: Fun Facts about Ruby — Volume 1

Please feel free to spread the word and share this post! 🙏

Thank you for your time!

redo for loops & enumerations

Ruby proposes a bunch of keywords that allows the developer to have control over loop & enumeration processing. This means that it can explicitly:

stop and exit a loop or an enumeration using the break keyword

keyword jump to the next iteration or step using the next keyword

keyword repeat the current iteration or step using the redo keyword

I prefer to talk about an iteration for a loop and a step for an enumeration.

In this article we’ll keep our focus on the redo keyword.

Let’s see how the redo keyword works within a loop

Here we see that the first iteration is infinitely repeated.

This is due to the fact that we call the redo keyword and that the for condition is never evaluated — so the i variable is never incremented.

Note that the After redo message is never printed out because the redo keyword stops the iteration and starts the repetition the moment it’s called.

We just have to increment i to bypass the if i == 1 statement

Here the loop ends up naturally while the first iteration is repeated once because of the explicit incrementation.

It works pretty similarly for enumerations

The redo keyword doesn’t work only on iteration and enumeration.

redo and blocks

In effect, the redo keyword can also be used within a simple block. It’ll then rerun the block from the beginning

Here our call to redo acts as a loop — an infinite loop in our case.

This is due to the fact that redo will rerun the block passed as argument of the hello method.

NB: feel free to have a look to Method Arguments in Ruby: Part II article if you’re unfamiliar with Proc objects.

We could stop the infinite loop by adding a condition to our redo .

Conclusion

The redo keyword can be useful in the context of a loop or an enumeration.

Unfortunately, this tool is widely unknown or unused among the Ruby developers.

Feel free to have a look to the Ruby tests (the redo_spec.rb file for example) to see some use cases of this keyword .

Also feel free to let a comment to describe a real use case of this keyword that you’ve encountered during your developer’s journey. 🗺️

Voilà !