相当于Ruby中的"继续"

Mar*_*ski 627 ruby continue keyword

在C和许多其他语言中,有一个continue关键字,当在循环内部使用时,会跳转到循环的下一个迭代.continueRuby中有这个关键字的等价物吗?

Ian*_*ton 905

是的,它被称为next.

for i in 0..5
   if i < 2
     next
   end
   puts "Value of local variable is #{i}"
end
Run Code Online (Sandbox Code Playgroud)

这输出如下:

Value of local variable is 2
Value of local variable is 3
Value of local variable is 4
Value of local variable is 5
 => 0..5 
Run Code Online (Sandbox Code Playgroud)

  • 这就是我记忆中的方式 - Ruby尊重Perl(`next`)高于C(`continue`) (12认同)
  • 专业提示:小心地将它与 `and` 一起使用,例如 `puts "Skipping" 和 next if i &lt; 2`,因为 `puts` 返回 `nil`,这是“错误的”,所以 `next` 不会被调用。 (4认同)

Nic*_*ore 106

next

另外,看一下当前迭代的redo重做.

  • ...因为红宝石就像那样. (36认同)
  • Ruby 借鉴了 Perl 的很多东西,包括 Perl 的 [`redo`](https://perldoc.perl.org/functions/redo.html) 命令(或者说它的本质)。对于 Ruby 的解释,请在[本页](https://ruby-doc.org/core-2.2.5/doc/syntax/control_expressions_rdoc.html)中搜索“redo”。 (2认同)

sbe*_*ley 82

用稍微惯用的方式写Ian Purton的答案:

(1..5).each do |x|
  next if x < 2
  puts x
end
Run Code Online (Sandbox Code Playgroud)

打印:

  2
  3
  4
  5
Run Code Online (Sandbox Code Playgroud)


sep*_*p2k 41

内部for循环和iterator方法each以及ruby中mapnext关键字将具有跳转到循环的下一次迭代的效果(与continueC中相同).

然而它实际上只是从当前块返回.因此,您可以将它与任何采用块的方法一起使用 - 即使它与迭代无关.

  • +22用于解释"next"的语义含义 (6认同)

19W*_*S85 29

Ruby有另外两个循环/迭代控制关键字:redoretry. 在Ruby QuickTips上阅读更多关于它们以及它们之间的区别.


idu*_*sun 8

我认为这是下一个.