在C和许多其他语言中,有一个continue关键字,当在循环中使用时,它会跳转到循环的下一个迭代。在Ruby中是否有与continue关键字相同的关键字?


当前回答

使用可以有条件地使用下一个

before = 0
"0;1;2;3".split(";").each.with_index do |now, i|
    next if i < 1
    puts "before it was #{before}, now it is #{now}"
    before = now
end

输出:

before it was 0, now it is 1
before it was 1, now it is 2
before it was 2, now it is 3

其他回答

使用可以有条件地使用下一个

before = 0
"0;1;2;3".split(";").each.with_index do |now, i|
    next if i < 1
    puts "before it was #{before}, now it is #{now}"
    before = now
end

输出:

before it was 0, now it is 1
before it was 1, now it is 2
before it was 2, now it is 3

是的,它叫next。

for i in 0..5
   if i < 2
     next
   end
   puts "Value of local variable is #{i}"
end

输出如下:

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 

next

另外,看看重做当前迭代的redo。

我想它叫next。

在for-loops和迭代器方法中,例如each和map the next关键字,在ruby中具有跳转到循环的下一次迭代的效果(与C中的continue相同)。

然而,它实际上所做的只是从当前块返回。所以你可以将它用于任何需要块的方法——即使它与迭代无关。