In C and many other languages, there is a continue
keyword that, when used inside of a loop, jumps to the next iteration of the loop. Is there any equivalent of this continue
keyword in Ruby?
702
votes
continue doesn't "restart" the loops but jumps to the next iteration of the loop.
– Matt Crinklaw-Vogt
@mlaw: I edited my question accordingly to prevent future confusion.
– Mark Szymanski
@dbr the duplicate you've found was asked after this one.
– Droogans
7 Answers
997
votes
95
votes
Writing Ian Purton's answer in a slightly more idiomatic way:
(1..5).each do |x|
next if x < 2
puts x
end
Prints:
2
3
4
5
43
votes
Inside for-loops and iterator methods like each
and map
the next
keyword in ruby will have the effect of jumping to the next iteration of the loop (same as continue
in C).
However what it actually does is just to return from the current block. So you can use it with any method that takes a block - even if it has nothing to do with iteration.
31
votes
Ruby has two other loop/iteration control keywords: redo
and retry
.
Read more about them, and the difference between them, at Ruby QuickTips.
9
votes
1
votes