在Ruby中,如何跳过.each循环中的循环,类似于“continue”
在Ruby中,如何跳过.each循环中的循环,类似于在其他语言中continue ?
使用next :
(1..10).each do |a| next if a.even? puts a end
打印:
1 3 5 7 9
额外的凉爽检查也redo然后retry 。
也适用于times , upto , downto , each_with_index , select , map和其他迭代器(更一般的块)的朋友。
有关更多信息,请参阅http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL 。
next – 这就像return ,但块! (所以你可以在任何proc / lambda使用它。)
这意味着你也可以说next n来从块中“返回” n 。 例如:
puts [1, 2, 3].map do |e| next 42 if e == 2 e end.inject(&:+)
这将产生46 。
请注意, return 总是返回从最接近的def ,而不是一个块; 如果没有周围的def , return是一个错误。
有意使用块内return可能会造成混淆。 例如:
def my_fun [1, 2, 3].map do |e| return "Hello." if e == 2 e end end
my_fun将导致"Hello." ,而不是[1, "Hello.", 2] ,因为return关键字属于外部def ,而不是内部block。