Ruby next Statement Tutorial

In this section, we will learn what the next statement is and how to use it in Ruby.

Note: we’re assuming you’re already familiar with the break statement.

The next Statement in Ruby

The Ruby next statement is used within the body of loops like (for loop or while loop) and is used to stop the current iteration of a loop and jump into the next iteration of that loop.

Basically, this next statement is a way of skipping the current iteration of a loop.

Ruby next Statement Syntax:

next

The next statement does not take any argument. Simply put, the statement in the block of a loop and it will skip the current iteration of that loop when the statement is called and the next iteration of that loop (if any) will start to run.

Example: while loop next statement

num = 0 
while num < 10
    num += 1
    if num <5
        next
    end 
    puts "The value of the num variable is: #{num}"
end 

puts "End"

Output:

The value of the num variable is: 5

The value of the num variable is: 6

The value of the num variable is: 7

The value of the num variable is: 8

The value of the num variable is: 9

The value of the num variable is: 10

End

The idea of this simple program is to print the values assigned to the `num` variable. But we can see that only numbers from 5 to 10 is printed to the output stream.

This is because for the first 5 iterations of the loop, a call to the `next` statement is triggered and that caused the current iteration of the loop to be stopped and the next one to begin. That’s why the first 5 values are skipped.

More to Read:

Ruby break Statement

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies