In Ruby, how do I skip a loop in a .each
loop, similar to continue
in other languages?
Use next
:
(1..10).each do |a|
next if a.even?
puts a
end
prints:
1
3
5
7
9
For additional coolness check out also redo
and retry
.
Works also for friends like times
, upto
, downto
, each_with_index
, select
, map
and other iterators (and more generally blocks).
For more info see http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL.