How to Use redo in Ruby: Syntax and Examples
In Ruby,
redo restarts the current iteration of a loop without checking the loop condition again. It is used inside loops like while, for, or each to repeat the current step immediately.Syntax
The redo keyword is used inside a loop to restart the current iteration without moving to the next one or re-checking the loop condition.
It can be used in loops such as while, until, for, and each.
Basic syntax:
loop do # some code redo if condition end
Here, if condition is true, the loop repeats the current iteration immediately.
ruby
loop do puts "Hello" redo if false break end
Output
Hello
Example
This example shows how redo repeats the current loop iteration when a condition is met, without moving forward.
ruby
i = 0 loop do i += 1 puts "Count: #{i}" if i == 3 puts "Redoing iteration when i is 3" redo end break if i >= 5 end
Output
Count: 1
Count: 2
Count: 3
Redoing iteration when i is 3
Count: 3
Redoing iteration when i is 3
Count: 3
Redoing iteration when i is 3
... (infinite loop)
Common Pitfalls
Using redo without changing the loop variables or conditions can cause an infinite loop because the same iteration repeats endlessly.
Always ensure that something changes inside the loop before redo is called to avoid this.
ruby
i = 0 loop do puts i redo if i == 0 # This causes infinite loop because i never changes i += 1 break if i > 2 end # Correct way: i = 0 loop do puts i if i == 0 i += 1 redo end break if i > 2 i += 1 end
Output
0
0
0
... (infinite loop)
0
1
2
Quick Reference
| Keyword | Description |
|---|---|
| redo | Restarts the current iteration of a loop without re-checking the condition |
| break | Exits the loop immediately |
| next | Skips to the next iteration of the loop |
| retry (legacy) | Used in older Ruby versions to restart the entire loop (deprecated) |
Key Takeaways
Use
redo inside loops to repeat the current iteration without re-evaluating the loop condition.Avoid infinite loops by ensuring loop variables or conditions change before calling
redo.redo works with loops like while, for, and each.Do not confuse
redo with next or break; redo repeats the same iteration.The
retry keyword is deprecated for loops; use redo instead.