Ruby - Next Statement
The next statement in Ruby let the program skip a block of codes for current iteration in a loop. Whenever next statement condition is fulfilled, it brings the program to the start of loop.
When the next statement is used in a nested loop (loop inside loop), it will skip innermost loop's code block, whenever condition is fulfilled.
Next statement with While loop
In the example below, next statement is used to skip the while loop if the value of variable j becomes 4.
j = 0 while j < 6 do j = j + 1 if j == 4 puts "this iteration is skipped." next end puts j end
The output of the above code will be:
1 2 3 this iteration is skipped. 5 6
Next statement with For loop
In the example below, next statement is used to skip the for loop if the value of variable i becomes 4.
for i in 1..6 if i == 4 puts "this iteration is skipped." next end puts i end
The output of the above code will be:
1 2 3 this iteration is skipped. 5 6
Next statement with Nested loop
The Next statement skip the inner loop's block of codes whenever condition is fulfilled. In below mentioned example, program skips the inner loop only when j = 100.
#Nested loop without next statement puts "# Nested loop without next statement" for i in 1..3 for j in [10, 100, 1000] puts i*j end end
The output of the above code will be:
# Nested loop without next statement 10 100 1000 20 200 2000 30 300 3000
#Nested loop with next statement puts "# Nested loop with next statement" for i in 1..3 for j in [10, 100, 1000] if j == 100 next end puts i*j end end
The output of the above code will be:
# Nested loop with next statement 10 1000 20 2000 30 3000