Control flow alterations in Ruby


In addition to loops, conditionals, and iterators, Ruby has some statements that are used to change the control flow in a program. In other words, these statements are pieces of code that execute one after the other until a condition is met.

In this article, we will explore the following control flow alterations in Ruby −

  • break statement

  • next statement

  • redo statement

  • retry statement

Let's consider each of these one by one.

break statement

When a condition is True in Ruby, the break statement terminates a loop.

Example

Consider the code shown below.

# break statement example
itr = 1

while true
   if itr * 6 >= 35
      break
   end
   puts itr * 6
   itr += 1
end

Output

It will produce the following output −

6
12
18
24
30

next statement

The next statement is used to jump to the next iteration of a loop in Ruby.

Example 

Consider the code shown below.

# next statement example
for tr in 0...10
   if tr == 6 then
      next
   end
   puts tr
end

Output

When we execute this code, it will produce the following output −

0
1
2
3
4
5
7
8
9

redo statement

Using the redo statement, you can restart an iterator or loop.

Example

Consider the code shown below.

# redo statement example

v = 0

while(v < 4)
   puts v
   v += 1

   # redo statement
   redo if v == 3
end

Output

It will produce the following output −

0
1
2
3

retry statement

retry statement is used to restart an iterator based on a condition or any method call from the start.

Example

Consider the code shown below.

# retry statement example
10.times do |itr|
   begin
      puts "Iteration #{itr}"
      raise if itr > 7
   rescue
      retry
   end
end

Output

When we execute this code, it will produce the following output −

Iteration 8
Iteration 8
Iteration 8
Iteration 8
Iteration 8
.
.
.

Updated on: 12-Apr-2022

171 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements