Ruby Language Reference

redo statement

Redo with While

The redo statement will jump to the point after the evaluation of the loop's conditional.

numbers = [1,2,3,4,5]
index = 0
repeat_count = 0

#  index < numbers.length is the loop's conditional
while index < numbers.length
  # This is the point where the redo executes the code again
  number = numbers[index]
  puts "The number is : #{number}"

  if number == 4
    repeat_count += 1
    redo if repeat_count < 3
  end

  index += 1
end

This prints:

The number is : 1
The number is : 2
The number is : 3
The number is : 4
The number is : 4
The number is : 4
The number is : 5

Redo within a Block

The redo within a block restarts yield when it used within a block.

def test
  yield
end

retry_attempt = 0

result = test do 
  p 'Connecting...'
  retry_attempt += 1
  redo if retry_attempt < 3
end

p result

This prints:

Connecting...
Connecting...
Connecting...
nil


Sharing is Caring