In the following article, we’re going to explore the following topics:
redofor loops & enumerations
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
- jump to the next iteration or step using the
- repeat the current iteration or step using the
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
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
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
NB: feel free to have a look to Method Arguments in Ruby: Part II article if you’re unfamiliar with
We could stop the infinite loop by adding a condition to our
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
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. 🗺️
May I have your attention please 🎤🎤
Feel free to subscribe here: www.rubycademy.com
Thank you for taking the time to read this post :-)
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.