HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrubyCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howsimilarcontinuerubyeachloopskip

Problem

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

Solution

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.

Code Snippets

(1..10).each do |a|
  next if a.even?
  puts a
end
1
3   
5
7
9

Context

Stack Overflow Q#4230322, score: 692

Revisions (0)

No revisions yet.