In Ruby, how do I skip a loop in a .each loop, similar to 'continue'

Blankman picture Blankman · Nov 20, 2010 · Viewed 179.9k times · Source

In Ruby, how do I skip a loop in a .each loop, similar to continue in other languages?

Answer

Jakub Hampl picture Jakub Hampl · Nov 20, 2010

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.