相当于Ruby中的“继续”

时间:2010-10-24 19:36:35

标签: ruby keyword continue

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

7 个答案:

答案 0 :(得分:872)

是的,它被称为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 

答案 1 :(得分:104)

next

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

答案 2 :(得分:75)

以稍微惯用的方式撰写Ian Purton's answer

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

打印:

  2
  3
  4
  5

答案 3 :(得分:39)

在for循环和迭代器方法(如eachmap内部,ruby中的next关键字将具有跳转到循环的下一次迭代的效果(与{{1相同)在C)。

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

答案 4 :(得分:28)

Ruby还有另外两个循环/迭代控制关键字:redoretryRead more about them, and the difference between them, at Ruby QuickTips

答案 5 :(得分:7)

我认为它被称为next

答案 6 :(得分: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

相关问题