Home »
Ruby Tutorial
Ruby redo and retry Statements
By IncludeHelp Last updated : November 16, 2024
Ruby is a very flexible language; it provides you many ways through which you can make your code more effective and clear. With the help of redo and retry statement, you can make your code more readable to the user as well as you can perform functionalities more efficiently. Let us go through the syntax, area of implementation and example of each of the statements.
Ruby redo Statement
redo statement comes into the scene when you have to re-execute the iteration in the same loop. It repeats the current iteration in the loop. The feature of the redo statement is that it executes without even evaluating the loop condition. Sometimes, this results in the creation of an infinite loop. Let us see the syntax and examples.
Syntax
while (#condition)
#statements
redo if #condition
end
Example 1
=begin
Ruby program to demonstrate redo
=end
i = 30
while(i < 50)
puts "Value of i is #{i}"
i += 1
redo if i == 50
end
Output
Value of i is 30
Value of i is 31
Value of i is 32
Value of i is 33
Value of i is 34
Value of i is 35
Value of i is 36
Value of i is 37
Value of i is 38
Value of i is 39
Value of i is 40
Value of i is 41
Value of i is 42
Value of i is 43
Value of i is 44
Value of i is 45
Value of i is 46
Value of i is 47
Value of i is 48
Value of i is 49
Value of i is 50
Explanation
In the above code, you can see that the condition specified in the while loop tells the iteration to be done up to 49 but due to the introduction of redo statement the iteration is going up to 50 because redo statement executes before the condition is checked.
Example 2
=begin
Ruby program to demonstrate redo
=end
i = 30
while(i < 50)
puts "Value of i is #{i}"
i += 1
redo if i > 45
end
Output
An infinite loop
Explanation
The above code will give an infinite loop because i will always be greater than 45.
Ruby retry Statement
In Ruby, the retry statement only works inside the begin/rescue block. You can also say that it works in the context of exception handling. You should use a retry statement when you want to re-execute the block.
Syntax
retry
Example
=begin
Ruby program to demonstrate retry
=end
for i in 0..10
begin
puts "VALUE OF i #{i}"
raise if i >= 9
rescue
retry
end
end
Output
Infinite loop.
Explanation
This will also give an infinite loop because exception will be raised until i>=9 and this is an infinite situation.