Break Statement in Ruby



In this tutorial, we will learn about the break statement in Ruby. We will cover the basics of using the break statement to exit loops prematurely.


What is a Break Statement

A break statement is used to terminate the execution of a loop. When a break statement is encountered, the loop immediately terminates, and the program continues with the next statement following the loop.


Syntax

The syntax for the break statement in Ruby is:

break

The break statement can be used in for, while, and until loops to exit the loop prematurely.



Example 1: Exiting a For Loop Early

We can use break statement in a for loop to exit a for loop early.

For example,

  1. Use a for loop to iterate over a range of numbers from 1 to 10.
  2. Inside the loop, use an if statement to check if the current number is equal to 5.
  3. If the condition is true, use a break statement to exit the loop.
  4. Print the current number.
  5. Without the break statement, the for loop could have iterated upto 10, but with a break statement, we could exit the for loop early based on a condition.

Ruby Program

for i in 1..10
  break if i == 5
  puts i
end

Output

1
2
3
4


Example 2: Exiting a While Loop Early

We can use break statement in a while loop to exit a while loop early.

For example,

  1. Declare a variable i and initialize it to 1.
  2. Use a while loop to iterate while i is less than or equal to 10.
  3. Inside the loop, use an if statement to check if i is equal to 5.
  4. If the condition is true, use a break statement to exit the loop.
  5. Print the value of i.
  6. Without the break statement, the while loop could have iterated upto 10, but with a break statement, we could exit the while loop early based on a condition.

Ruby Program

i = 1
while i <= 10
  break if i == 5
  puts i
  i += 1
end

Output

1
2
3
4


Example 3: Exiting a Loop Within a Loop

We can use break statement in nested loops also.

For example,

  1. Use nested loops to iterate over rows and columns of a 2D array.
  2. Inside the nested loops, use an if statement to check if a specific condition is met.
  3. If the condition is true, use a break statement to exit the immediate loop which is inner loop in this case.

Ruby Program

3.times do |i|
  3.times do |j|
    puts "(#{i}, #{j})"
    break if i == j && i == 1
  end
end

Output

(0, 0)
(0, 1)
(0, 2)
(1, 0)
(1, 1)
(2, 0)
(2, 1)
(2, 2)