【问题标题】:Equivalent of "continue" in Ruby相当于 Ruby 中的“继续”
【发布时间】:2011-04-29 22:20:07
【问题描述】:

在 C 和许多其他语言中,有一个 continue 关键字,当在循环内使用时,它会跳转到循环的下一次迭代。 Ruby 中有没有与 continue 关键字等效的东西?

【问题讨论】:

  • continue 不会“重新启动”循环,而是跳转到循环的下一次迭代。
  • @mlaw:我相应地编辑了我的问题,以防止将来出现混淆。
  • @dbr 你找到的副本是在这个之后被问到的。

标签: ruby keyword continue


【解决方案1】:

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

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

【讨论】:

  • 以及漂亮的重做声明
【解决方案2】:

我想它叫next

【讨论】:

    【解决方案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 
    

    【讨论】:

    • 这就是我的记忆——Ruby 尊重 Perl (next) 高于 C (continue)
    • 专业提示:小心使用 andputs "Skipping" and next if i &lt; 2,因为 puts 返回 nil,这是“错误的”,所以 next 不会被调用。
    【解决方案4】:

    next

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

    【讨论】:

    • ...因为 ruby​​ 就是这样。
    • Ruby 借鉴了 Perl 的很多东西,包括 Perl 的 redo 命令(或者说它的本质)。对于Ruby的解释,在this page中搜索“redo”。
    【解决方案5】:

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

    【讨论】:

      【解决方案6】:

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

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

      打印:

        2
        3
        4
        5
      

      【讨论】:

        【解决方案7】:

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

        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()
        

        输出: 输入编号 10

        1 2 3 4 6 7 8 9 10

        【讨论】:

          猜你喜欢
          • 2010-11-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-27
          • 2014-02-19
          • 1970-01-01
          相关资源
          最近更新 更多