本文翻译自:In Ruby, how do I skip a loop in a .each loop, similar to 'continue' [duplicate]
This question already has an answer here: 这个问题在这里已有答案:
In Ruby, how do I skip a loop in a .each
loop, similar to continue
in other languages? 在Ruby中,如何跳过.each
循环中的循环,类似于在其他语言中continue
?
参考:https://stackoom.com/question/HkV0/在Ruby中-如何跳过-each循环中的循环-类似于-continue-duplicate
Use next
: 使用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
. 如需额外的凉爽,请查看redo
retry
。
Works also for friends like times
, upto
, downto
, each_with_index
, select
, map
and other iterators (and more generally blocks). 也适用于朋友喜欢times
, upto
, downto
, each_with_index
, select
, map
和其他迭代器(和更普遍块)。
For more info see http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL . 有关详细信息,请参阅http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL 。
next
- it's like return
, but for blocks! next
- 就像return
一样,但对于积木! (So you can use this in any proc
/ lambda
too.) (所以你也可以在任何proc
/ lambda
使用它。)
That means you can also say next n
to "return" n
from the block. 这意味着您还可以说next n
n
从块中“返回” n
。 For instance: 例如:
puts [1, 2, 3].map do |e|
next 42 if e == 2
e
end.inject(&:+)
This will yield 46
. 这将产生46
。
Note that return
always returns from the closest def
, and never a block; 请注意, return
总是从最接近的def
返回,而不是块; if there's no surrounding def
, return
ing is an error. 如果没有周围的def
,则return
是一个错误。
Using return
from within a block intentionally can be confusing. 故意使用块内的return
可能会令人困惑。 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."
my_fun
将导致"Hello."
, not [1, "Hello.", 2]
, because the return
keyword pertains to the outer def
, not the inner block. ,而不是[1, "Hello.", 2]
,因为return
关键字属于外部def
,而不是内部块。