How to use the 'break' and 'next' statements in Ruby?

RubyServer Side ProgrammingProgramming

break Statement in Ruby

In Ruby, we use the break statement in order to make sure that we exit a certain loop after a condition. For example, suppose we want to print the numbers from 1 to 10, but once we hit the number 5, we just don't want the loop to print any numbers that come after it. In such a case, we can use the break statement.

Example 1

Let's take an example and understand how the break statement works in Ruby. Consider the code shown below.

# break statement in Ruby
#!/usr/bin/ruby -w

itr = 1

# while Loop
while true
   puts itr * 5
   itr += 1

   if itr * 3 >= 25
      # Break Statement
      break
   end
end

Output

It will produce the following output −

5
10
15
20
25
30
35
40

Example 2

Let's take another example. Consider the code shown below.

# break statement in Ruby
#!/usr/bin/ruby -w

itr = 0
   # Using while
   while true do

      puts itr
      itr += 1

   # Using Break Statement
   break if itr > 5
end

Output

It will produce the following output −

0
1
2
3
4
5

next Statement in Ruby

The next statement is used to skip a particular iteration of a loop. For example, let's say that we want to print the numbers from 1 to 7, but do not want to print the number 5. In such a case, we can use the next statement.

Example 3

Let's take an example to demonstrate how it works. Consider the code shown below.

# next statement in Ruby
#!/usr/bin/ruby -w

for x in 0..5
   if x+1 < 3 then
      # next statement
      next
   end
   puts "x contains : #{x}"
end

Output

It will produce the following output −

x contains : 2
x contains : 3
x contains : 4
x contains : 5

Example 4

Let's take another example. Consider the code shown below.

for i in 6...13
   if i == 8 then
      next
   end
   puts i
end

Output

On execution, we will get the following output −

6
7
9
10
11
12
raja
Updated on 12-Apr-2022 07:19:38

Advertisements