Home »
Ruby Tutorial
Ruby Break Statement
By IncludeHelp Last updated : November 16, 2024
Ruby break Statement
In programming, loops are needed to be terminated properly otherwise it will result in an infinite loop. In ruby, when a certain condition is met, loops are terminated via break statement. The break statement is mostly used in while loop where the value is required to be printed till the condition comes out to be true.
The basic purpose of break statement is to discontinue the loop and it is called from inside the loop.
Syntax
break
Now, let us understand the implementation of a break statement in a Ruby program with the help of program codes.
Example 1
=begin
Ruby program to demonstrate the use of the Break statement
in a while loop.
=end
puts "Enter the integer to calculate table:"
num = gets.chomp.to_i
j = 1
# Using While Loop to print multiplication table
while true
# Printing values
tab = j * num
puts "#{num} * #{j} = #{tab}"
j += 1
# Break when j exceeds 10
if j > 10
break # Exits the loop when the table is complete
end
end
Output
RUN 1:
Enter the integer to calculate table
12
12 * 1 = 12
12 * 2 = 24
12 * 3 = 36
12 * 4 = 48
12 * 5 = 60
12 * 6 = 72
12 * 7 = 84
12 * 8 = 96
12 * 9 = 108
12 * 10 = 120
RUN 2:
Enter the integer to calculate table
9
9 * 1 = 9
9 * 2 = 18
9 * 3 = 27
9 * 4 = 36
9 * 5 = 45
9 * 6 = 54
9 * 7 = 63
9 * 8 = 72
9 * 9 = 81
9 * 10 = 90
Explanation
In the above code, we are trying to demonstrate the significance of the break statement. We have written a code which is calculating the table of the number which is being provided by the user. We are giving a call to break statement inside 'if' condition which is working inside the 'while' loop. The break statement is working in the way that it is breaking the loop execution or you can say that it is terminating the loop when the value of j (loop variable) exceeds 10.
Example 2
=begin
Ruby program to demonstrate the use of the Break statement
in a while loop.
=end
k = 1
# Using while loop to print values
while true do
# Printing value: k * (k-1)
puts k * (k - 1)
k += 1
# Using Break Statement to exit the loop when k > 5
break if k > 5
end
Output
0
2
6
12
20
Here, the break statement is terminating loop when it finds the value of 'k' is greater than 5.