So far we have looked at various types of loops, e.g. while loops, for loops,….etc.
What ever type of loop you are using, there will be times when you want to one of the following:
- skip to the next iteration while part way through the current interation – this is done using the “next” keyword
- exit the loop early – this is done using the “break” keyword.
- redo the current iteration – this is done using the “redo” keyword.
We will demonstrate the next/break/redo keywords using a simple for-loop (although they can work in any type of loop)
Skipping a current loop iteration – using “next”
for i in (1..5) next if i == 3 puts i end
PS C:\Temp\irb> ruby .\nextloop.rb 1 2 4 5 PS C:\Temp\irb>
Exiting the whole loop early – using “break”
Here’s an example:
for i in (1..5) break if i == 3 puts i end
PS C:\Temp\irb> ruby .\breakloop.rb 1 2 PS C:\Temp\irb>
The break keyword has an extra feature for catching an output from a loop when the break keyword gets triggered, here’s an example of how this works:
answer = for i in (1..5) break "loop exited early" if i == 3 puts i end # outputs: 1 2 puts answer # this outputs "loop exited early"
This technique could be useful for various purposes, including capturing possible error messages and storing it into logs.
Redoing the current iteration of a loop – using “redo”
Here’s an example of the redo key-word in action:
for i in (1..5) i += 1 # I had to add this line in to avoid an infinite loop. redo if i == 3 puts i end
PS C:\Temp\irb> ruby .\redoloop.rb 2 4 4 5 6 PS C:\Temp\irb>