在Ruby中,如何跳过.each循环中的循环,类似于'continue'

Bla*_*man 316 ruby iteration syntax loops

在Ruby中,如何在循环中跳过.each循环,类似于continue其他语言?

Jak*_*mpl 557

用途next:

(1..10).each do |a|
  next if a.even?
  puts a
end
Run Code Online (Sandbox Code Playgroud)

打印:

1
3   
5
7
9
Run Code Online (Sandbox Code Playgroud)

有关更多的凉意退房还redoretry.

也适用于这样的朋友times,upto,downto,each_with_index,select,map和其他迭代器(和更普遍块).

有关详细信息,请参阅http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL.

  • 并且'打破'.... (6认同)
  • 在这种情况下,中断是错误的答案。它停止.each而不只是保持1个循环。;) (2认同)

Ash*_*she 48

next- 它就像return,但是对于块!(所以你可以在任何proc/中使用它lambda.)

这意味着你也可以说从块中next n"返回" n.例如:

puts [1, 2, 3].map do |e|
  next 42 if e == 2
  e
end.inject(&:+)
Run Code Online (Sandbox Code Playgroud)

这会产生46.

请注意,return 始终从最近的def,而不是块返回; 如果没有周围def,returning是一个错误.

return故意在块内使用可能会造成混淆.例如:

def my_fun
  [1, 2, 3].map do |e|
    return "Hello." if e == 2
    e
  end
end
Run Code Online (Sandbox Code Playgroud)

my_fun将导致"Hello.",而不是[1, "Hello.", 2]因为return关键字属于外部def,而不是内部块.