在Ruby中,如何跳过.each循环中的循环,类似于‘continue‘[duplicate]

本文翻译自:In Ruby, how do I skip a loop in a .each loop, similar to 'continue' [duplicate]

This question already has an answer here: 这个问题在这里已有答案:

  • Equivalent of “continue” in Ruby 7 answers 相当于Ruby 7答案中 的“继续”

In Ruby, how do I skip a loop in a .each loop, similar to continue in other languages? 在Ruby中,如何跳过.each循环中的循环,类似于在其他语言中continue


#1楼

参考:https://stackoom.com/question/HkV0/在Ruby中-如何跳过-each循环中的循环-类似于-continue-duplicate


#2楼

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). 也适用于朋友喜欢timesuptodowntoeach_with_indexselectmap和其他迭代器(和更普遍块)。

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 。


#3楼

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 ,而不是内部块。

你可能感兴趣的:(ruby,loops,syntax,iteration)