Home »
Ruby Tutorial
Ruby next statement
By IncludeHelp Last updated : November 16, 2024
Ruby next Statement
You must have gone through the implementation of continue statement in other programming languages, Ruby next statement works in the same way as continue does for other programming languages.
The next statement is used to skip the remaining part of the current iteration. When the next statement is found, no further processing in the current iteration will be performed; it will enter the next iteration.
Syntax
next
There is nothing much to describe the next statement. Let us go through its example for better clarity of the concept.
Example 1
=begin
Ruby program to demonstrate use of Next statement.
=end
puts "Enter the integer you want to escape (Range 1 to 20)"
num = gets.chomp.to_i
if(num >= 1 && num <= 20)
puts "Numbers except #{num} are:"
for p in 1..20
if p == num then
next
end
puts p
end
else
puts "Error: Out of Range"
end
Output
RUN 1:
Enter the integer you want to escape (Range 1 to 20)
1
Numbers except 1 are:
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
RUN 2:
Enter the integer you want to escape (Range 1 to 20)
45
Error: Out of Range
Explanation
In the above code, we are employing ‘next’ statement to escape from printing the number which is inputted by the user. Firstly, we are checking the range, if the number is under the range, then further processing is taking place otherwise program will print "Error : Out of Range ". We are printing all the numbers except the number which is provided by the user.
Example 2
=begin
Ruby program to demonstrate use of Next statement.
=end
puts "Enter the Upper Range"
ur = gets.chomp.to_i
puts "Enter the Lower Range"
lr = gets.chomp.to_i
for p in lr..ur
if (p % 2 != 0) then
next
end
puts "#{p} is even"
end
Output
Enter the Upper Range
40
Enter the lower Range
10
10 is even
12 is even
14 is even
16 is even
18 is even
20 is even
22 is even
24 is even
26 is even
28 is even
30 is even
32 is even
34 is even
36 is even
38 is even
40 is even
Explanation
In the above program, we have implemented next statement to find the even numbers from the range provided by the user. next statement is working in the way that it is skipping the odd numbers. The odd numbers are being checked by the condition written. The code becomes simpler with the help of next statement.