The redo Keyword in Ruby

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

  • redo for loops & enumerations
  • redo and blocks
Before to start, feel free to have a look to my new eBook: 📖Ruby Object Model📖💎

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
  • jump to the next iteration or step using the next 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à !


Thank you for taking the time to read this post :-)

💎💎Here’s a link to my new ebook project 📖Ruby Object Model📖 !! 💎💎

Feel free to 👏 and share this article if it has been useful for you. 🚀

Here is a link to my last article: refine and using Methods in Ruby: Part I.