716

在 C 和许多其他语言中,有一个continue关键字在循环内使用时会跳转到循环的下一次迭代。continueRuby中是否有与 this 关键字等价的关键字?

4

7 回答 7

1019

是的,它叫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 
于 2010-10-24T19:41:09.183 回答
119

next

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

于 2010-10-24T19:41:59.123 回答
98

以一种更惯用的方式写Ian Purton 的答案:

(1..5).each do |x|
  next if x < 2
  puts x
end

印刷:

  2
  3
  4
  5
于 2012-06-25T17:50:55.947 回答
43

在 for 循环和迭代器方法中,如ruby​​ 中的each和关键字将具有跳转到循环的下一个迭代的效果(与C 中相同)。mapnextcontinue

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

于 2010-10-24T19:40:36.397 回答
32

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

于 2010-10-24T23:09:51.423 回答
9

我认为它被称为next

于 2010-10-24T19:40:56.647 回答
1

使用下一个,它将绕过该条件,其余代码将起作用。下面我提供了完整的脚本并输出

class TestBreak
  puts " Enter the nmber"
  no= gets.to_i
  for i in 1..no
    if(i==5)
      next
    else 
      puts i
    end
  end
end

obj=TestBreak.new()

输出:输入 nmber 10

1 2 3 4 6 7 8 9 10

于 2019-07-29T08:20:46.953 回答