首页 文章

相当于Ruby中的“继续”

提问于
浏览
573

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

6 回答

  • 37

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

    next

    另外,请查看 redo ,它会重做当前的迭代 .

  • 27

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

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

    打印:

    2
      3
      4
      5
    
  • 96

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

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

  • 69

    Ruby有两个其他循环/迭代控制关键字: redoretry . Read more about them, and the difference between them, at Ruby QuickTips .

  • 7

    我认为它被称为next .

相关问题