In Ruby, how do I skip a loop in a .each loop, similar to continue in other languages?
2 Answers
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.
- 78,473
- 57
- 200
- 338
- 39,863
- 10
- 77
- 106
-
Yes, though break isn't that cool (and is a lot more useful ;). – Jakub Hampl Nov 19 '10 at 23:47
-
3break is a wrong answer in this case. It stop the .each not just keep 1 loop. ;) – thanhnha1103 Jun 20 '16 at 10:39
next - it's like return, but for blocks! (So you can use this in any proc/lambda too.)
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 46.
Note that return always returns from the closest def, and never a block; if there's no surrounding def, returning is an error.
Using 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 "Hello.", not [1, "Hello.", 2], because the return keyword pertains to the outer def, not the inner block.
- 18,948
- 5
- 53
- 72
-
1It would be more interesting to give an example of the `next n`, instead of the `return foo`. – ANeves Sep 26 '13 at 12:04
-
1@ANeves thanks for feedback; have revised to better contrast `next`/`return`. – Asherah Sep 26 '13 at 14:06