Skip to content
Related Articles

Related Articles

Ruby redo and retry Statement
  • Last Updated : 17 Sep, 2019

In Ruby, Redo statement is used to repeat the current iteration of the loop. redo always used inside the loop. The redo statement restarts the loop without evaluating the condition again.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program of using redo statement
  
#!/usr/bin/ruby
restart = false
  
# Using for loop
for x in 2..20
    if x == 15
        if restart == false
  
            # Printing values
            puts "Re-doing when x = " + x.to_s
            restart = true
  
            # Using Redo Statement
            redo
        end
    end
    puts x
end

chevron_right


Output:

2
3
4
5
6
7
8
9
10
11
12
13
14
Re-doing when x = 15
15
16
17
18
19
20

In above example, redo statement apply when x = 15.

retry Statement:

To repeat the whole loop iteration from the start the retry statement is used. retry always used inside the loop.

Example #1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program of retry statement
  
# Using do loop
10.times do |i|
  begin
    puts "Iteration #{i}"
    raise if i > 2
  rescue
  
    # Using retry
    retry
  end
end

chevron_right


Output:

Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 3
Iteration 3
...

Example #2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program of retry statement
def geeks
  attempt_again = true
  p 'checking'
  begin
  
    # This is the point where the control flow jumps
    p 'crash'
    raise 'foo'
      rescue Exception => e
        if attempt_again
          attempt_again = false
  
      # Using retry
      retry       
    end
  end
end

chevron_right





My Personal Notes arrow_drop_up
Recommended Articles
Page :