Home » Ruby programming

Ruby break statement

break statement in Ruby: Here, we are going to learn about the break statement in Ruby programming language with syntax and example.
Submitted by Hrithik Chandra Prasad, on September 02, 2019

break statement in Ruby

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 use of Break statement.
=end

puts "Enter the integer to calculate table"
num = gets.chomp.to_i

	j = 1

	# Using While Loop 
	while true

		# Printing Values 
		tab = j * num
		puts "#{num} * #{j} = #{tab}"
		j += 1
		if j > 10

			# Using Break Statement 
			break
		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

Code logic:

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 use of Break statement.
=end

k = 1

# Using while 
while true do

    # Printing Value 
    puts k * (k-1) 
    k += 1
    
    # Using Break Statement 
    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.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.