ruby
  1. ruby-break-next

Ruby break and next Statement

The break and next statement in Ruby are used to control the flow of a loop. The break statement can be used to exit a loop completely, while the next statement can be used to skip to the next iteration of a loop.

Syntax

  • break statement:

    break
    break expression
    
  • next statement:

    next
    next expression
    

Example

Using break statement

The following example uses the break statement to exit the loop when the counter reaches 3.

count = 0

while count < 5 do
  puts "Count: #{count}"
  if count == 3
    break
  end
  count += 1
end

Output:

Count: 0
Count: 1
Count: 2
Count: 3

Using next statement

The following example uses the next statement to skip even numbers in the loop.

count = 0

while count < 5 do
  count += 1
  if count % 2 == 0
    next
  end
  puts "Count: #{count}"
end

Output:

Count: 1
Count: 3
Count: 5

Explanation

break statement

The break statement is used to exit a loop. When the break statement is encountered, the loop is terminated and execution of the program continues with the next statement after the loop.

By default, the break statement exits only the innermost loop. However, it can be combined with a label to exit from an outer loop as well.

next statement

The next statement is used to skip to the next iteration of a loop. When the next statement is encountered, the loop jumps immediately to the next iteration and skips all the remaining statements in the loop for the current iteration.

Use

The break and next statements are usually used in loops to control their flow.

  • Use break statement to exit a loop when a certain condition is met.
  • Use next statement to skip specific iterations of a loop.

Important Points

  • The break and next statements can only be used within a loop.
  • The break statement exits the loop completely, and the next statement skips to the next iteration of the loop.
  • The break and next statements can be used with a label to exit from an outer loop or skip to the next iteration of an outer loop.
  • When using multiple nested loops, the break and next statement applies only to the innermost loop.

Summary

  • The break statement is used to exit a loop completely.
  • The next statement is used to skip to the next iteration of a loop.
  • The break and next statements are usually used in loops to control their flow.
  • They can be used with a label to exit from or skip to an outer loop.
  • When using multiple nested loops, they apply only to the innermost loop.
Published on: