Ruby Tutorial Ruby Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

Ruby - Redo Statement



The break statement in Ruby is used to terminate the program out of the loop containing it whenever the condition is met.

If the break statement is used in a nested loop (loop inside loop), it will terminate innermost loop after fulfilling the break criteria.

The Repeat Loop

The repeat loop in R is used to execute a set of statements again and again until the stop condition is met. The specify the stop condition a break statement is used.

Syntax

repeat {
  statements
  if (condition) {
    break
  }
}

Flow Diagram:

R Repeat Loop

Example

In example below, repeat loop is used to print numbers from 1 to 5.

i <- 1

#print numbers from 1 to 5
repeat {
  print(i)
  i <- i + 1
  
  #breaks the loop at i = 6
  if(i == 6)
    break
}

The output of the above code will be:

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

next statement

By using next statement, the program skips the loop whenever condition is met, and brings the program to the start of loop. Please consider the example below.

i <- 1

#skips the loop for odd value of i
repeat {
  #breaks the loop at i = 10
  if(i == 10)
    break 

  #skips the loop for odd i
  if(i %% 2 == 1) {
    i <- i + 1
    next
  } 

  print(i)
  i <- i + 1
}

The output of the above code will be:

[1] 2
[1] 4
[1] 6
[1] 8

5