This question already has an answer here:
Equivalent of “continue” in Ruby
(1..10).each do |a| next if a.even? puts a end
1 3 5 7 9
For additional coolness check out also
Works also for friends like
map and other iterators (and more generally blocks).
For more info see http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL.
next – it’s like
return, but for blocks! (So you can use this in any
That means you can also say
next n to “return”
n from the block. For instance:
puts [1, 2, 3].map do |e| next 42 if e == 2 e end.inject(&:+)
This will yield
return always returns from the closest
def, and never a block; if there’s no surrounding
returning is an error.
return from within a block intentionally can be confusing. For instance:
def my_fun [1, 2, 3].map do |e| return "Hello." if e == 2 e end end
my_fun will result in
[1, "Hello.", 2], because the
return keyword pertains to the outer
def, not the inner block.