ruby
  1. ruby-redo-retry

Ruby Redo Retry

In Ruby, redo and retry are keywords used to control the flow of a program. They are mainly used in loops to repeat the process or to start it over from the beginning.

Syntax

# redo
do_something if condition
redo if condition

# retry
begin
  do_something
rescue SomeException => e
  retry if condition
end

Example

Redo

i = 0
while i < 3
  puts "Iteration #{i}"
  i += 1
  redo if i == 2
end

Output:

Iteration 0
Iteration 1
Iteration 1
Iteration 2

Explanation:

In the above example, the redo keyword is used to repeat the iteration when the value of i is equal to 2. This causes the second iteration to be repeated, resulting in two printouts of "Iteration 1".

Retry

begin
  puts "Enter a number: "
  num = Integer(gets.chomp)
rescue ArgumentError
  puts "Invalid input. Please enter a number."
  retry
end

Output:

Enter a number:
hello
Invalid input. Please enter a number.
5

Explanation:

In the above example, the retry keyword is used to go back to the beginning of the begin block and ask the user to enter a number again when an ArgumentError is raised due to an invalid input. This process will continue until the user enters a valid input.

Use

Redo

redo is mostly used for repeating the current iteration in loops. It can be used when you need to re-do an operation without going through the entire loop iteration again.

Retry

retry is typically used in rescue blocks to try the same block of code again when an exception is raised. It can be used when you need to make sure that a block of code is executed successfully, even if an error is thrown.

Important Points

  • The redo keyword repeats the current iteration in a loop, while the retry keyword repeats a block of code in a begin and rescue block.
  • The redo keyword can only be used inside a loop, whereas the retry keyword can only be used inside a begin and rescue block.
  • Both keywords are useful tools for controlling the flow of a program and handling errors.

Summary

redo and retry are two powerful keywords in Ruby that are used to control the flow of a program and handle errors. While redo is used to repeat the current iteration in a loop, retry is used to repeat a block of code in a begin and rescue block. By understanding how and when to use these two keywords, you can write more efficient and flexible code in Ruby.

Published on: