For example, we can use the continue keyword in a “for” loop to skip over a given iteration to the next one. This skips any code that comes after it in the current iteration.
However, we do not have access to the continue keyword in Ruby. Instead, we use the next keyword to accomplish the same task.
This tutorial explores how we can use the next keyword in Ruby to skip over an iteration from a loop, etc.
Ruby Next Keyword
As mentioned, the next keyword in Ruby is similar to the continue keyword in other programming languages. We can use it in a given loop to skip the rest of the current iteration and move on to the next iteration.
For example, we can use it inside a “for” loop as demonstrated in the following code sample:
irb(main):023:1> next if i % 2 == 0
irb(main):024:1> puts i
irb(main):025:1> end
The previous example code prints the odd numbers from 1 to 10. The next if i % 2 == 0 statement checks if the current value of i is even. If it is, the next statement is executed which causes the loop to move on to the next iteration without executing the puts statement.
The resulting output is as follows:
3
5
7
9
=> 1..10
We can also use the next keyword within a “while” and “until” loops. The functionalities remain the same.
Take the following example code:
irb(main):029:1> next if i % 2 == 0
irb(main):030:1> puts i
irb(main):031:1> end
This should work similarly as the “for” loop as demonstrated in the following sample output:
3
5
7
9
=> nil
It is good to keep in mind that the next keyword is a reserved keyword in Ruby. Hence, avoid using it as a variable, function, or identifier in your code.
Conclusion
You discovered the next keyword in Ruby which is used within a loop to skip the rest of the current iteration and move on to the next iteration. You also learned how the keyword is used in for, while, and until loops with examples. We hope that this tutorial provided a clear understanding of how to use the next keyword in Ruby and how it can be a valuable tool to control the flow of your loops.