Ruby Tutorial Ruby References

Ruby - Redo and Retry Statements



Redo statement

The redo statement in Ruby is used to repeat the current iteration of the loop. It is always used inside the loop. It restarts the loop without checking loop condition.

Example

The example below shows the usage of redo statement.

restart = true
  
#using redo inside for loop
for i in 1..10
  
  #repeating loop when conditions met
  if i == 5 and restart == true 
    puts "Repeating loop when i = #{i}"
    restart = false
  
    #using redo statement
    redo
  end
  
  puts i
end

The output of the above code will be:

1
2
3
4
Repeating loop when i = 5
5
6
7
8
9
10

Retry statement

The retry statement in Ruby is used to repeat the whole loop iteration from the start. It is always used inside the loop.

Example

The example below shows the usage of retry statement.

retry_again = 1

#using retry inside for loop
for i in 1..5
  begin
    puts "i = #{i}"

    raise if i >= 3
  rescue
    #using retry statement 
    #retry_again variable is used to run
    #the retry statement 4 times
    #without this condition program will
    #keep on printing i = 3
    retry if (retry_again += 1) < 5
  end
end

The output of the above code will be:

i = 1
i = 2
i = 3
i = 3
i = 3
i = 3
i = 4
i = 5