The redo Keyword in Ruby
In the following article, we’re going to explore the following topics:
redo
for loops & enumerationsredo
and blocks
redo for loops & enumerations
Ruby proposes a bunch of keywords that allow 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 variable i
is never incremented.
Note that After redo
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
doesn’t work only on iteration and enumeration.
redo and blocks
Indeed, redo
can also be used within a simple block. It’ll then rerun the block from the beginning
Here, the 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 an 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 Ruby developers.
Feel free to have a look at the Ruby tests (the redo_spec.rb
file for example) to see some use cases for 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. 🗺️
Ruby Mastery
We’re currently finalizing our first online course: Ruby Mastery.
Join the list for an exclusive release alert! 🔔
Also, you can follow us on x.com as we’re very active on this platform. Indeed, we post elaborate code examples every day.
💚