Ruby Continue Statement


Ruby Continue Statement

In this tutorial, we will learn about the next statement in Ruby. We will cover the basics of using the next statement to skip the current iteration of a loop and proceed with the next iteration.


What is a Next Statement

A next statement is used to skip the current iteration of a loop and proceed with the next iteration. When a next statement is encountered, the remaining code inside the loop for the current iteration is skipped, and the loop continues with the next iteration.


Syntax

The syntax for the next statement in Ruby is:

next

The next statement can be used in for loops, while loops, and until loops to skip the current iteration and proceed with the next iteration.



Skipping Even Numbers in a For Loop

We can use next statement in a for loop to skip loop execution for even numbers while iterating over a range of numbers.

For example,

  1. Use a for loop to iterate from 1 to 10.
  2. Inside the loop, use an if statement to check if the current iteration is even.
  3. If the condition is true, use a next statement to skip the current iteration.

Ruby Program

for i in 1..10
  if i.even?
    next
  end
  puts i
end

Output

1
3
5
7
9


Skipping Odd Numbers in a While Loop

We can use next statement in a while loop to skip loop execution for odd numbers while iterating over a range of numbers.

For example,

  1. Declare an integer variable i and initialize it to 1.
  2. Use a while loop to iterate while i is less than or equal to 10.
  3. Inside the loop, use an if statement to check if i is odd.
  4. If the condition is true, use a next statement to skip the current iteration.

Ruby Program

i = 1
while i <= 10
  if i.odd?
    i += 1
    next
  end
  puts i
  i += 1
end

Output

2
4
6
8
10