Ruby

Continue Keyword in Ruby

You may be familiar with the continue keyword if you come from other programming languages. In most programming languages, the continue keyword is used within a loop to skip the rest of the current iteration and continue with the next iteration. This can be useful when skipping specific iterations based on certain conditions.

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):022:0> for i in 1..10
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:

1
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):027:0> while i    i += 1
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:

1
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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list