Like the if statements you saw 2 posts prior, there are many ways to construct loops. Not that there is no increment/decrement, ++/--
, operation in Ruby.
There is the while loop you’re used to
1 2 3 4 5 6 7 8 |
|
While loops with the test at the end
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
There’s the until loops which run while the condition is false
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
And finally, my favourite – the for loops. If you already have a list to iterate through, great.
1 2 3 4 5 6 7 |
|
If not, it’s great too
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
There’s also 4 keywords to help you manage the control of flow break
, next
, redo
and finally retry
which I’ll bring up in the Error Handling section. break
exits the inner most loop
1 2 3 4 5 6 7 8 |
|
While next
jumps to the next iteration of the loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
And redo
jumps back to the beginning of the current iteration in this loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|