Introduction
In addition to loops, conditionals, and iterators, the Ruby programming language has various statements to alter the control flow in a program. In other words, these statements are a piece of code that executes one after the other until the condition is true, and then the code terminates.
The following statements can alter the control flow in a Ruby program:
- The break statement
- The next statement
- The redo statement
- The retry statement
- The return statement
- The throw/catch statement
In this blog, we will discuss altering the control flow using the next statement.
So, let us get started:
The next statement
We utilise the next statement to skip the remainder of the current iteration. There won't be any further iterations after the next statement is executed. In every other language, a next statement is equivalent to a “continue” statement.
To be precise, the next statement skips the current iteration of the loop and begins the next iteration.
Let us see the syntax for altering the control flow using the next statement.
Syntax
next
Example - 1
The codes given below show altering the control flow using the next statement.
# Ruby program for altering the control flow using the next statement
for x in 1..7
# Used condition
if x < 3 then
# Using the next statement
next
end
# Printing values
puts "Value of x is : #{x}"
End
Output
The code above produces the output given below:
Explanation
In the above example, we are checking if the variable x is smaller than 3 or not. If yes, then skip the iteration by using the next keyword.
Once x becomes greater than 3, print its value.
Let us see another example that shows altering the control flow using the next statement.
Example - 2
# Ruby program for altering the control flow using the next statement
i = 0
while true
if i*5 >= 20
next
end
puts i*5
i += 1
end
Output
The code above gives the following output:
Explanation
In the above example, we are checking if the variable the statement i * 5 is greater than 20 or not. Using the next keyword, we are stopping our program to go beyond the value of 20. Hence, it always prints values less than 20.