Equivalent of “continue” in Ruby

后端 未结 7 1339
离开以前
离开以前 2020-12-07 07:13

In C and many other languages, there is a continue keyword that, when used inside of a loop, jumps to the next iteration of the loop. Is there any equivalent of

相关标签:
7条回答
  • 2020-12-07 07:40

    Use next, it will bypass that condition and rest of the code will work. Below i have provided the Full script and out put

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

    Output: Enter the nmber 10

    1 2 3 4 6 7 8 9 10

    0 讨论(0)
  • 2020-12-07 07:44

    Writing Ian Purton's answer in a slightly more idiomatic way:

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

    Prints:

      2
      3
      4
      5
    
    0 讨论(0)
  • 2020-12-07 07:48

    next

    also, look at redo which redoes the current iteration.

    0 讨论(0)
  • 2020-12-07 07:50

    Ruby has two other loop/iteration control keywords: redo and retry. Read more about them, and the difference between them, at Ruby QuickTips.

    0 讨论(0)
  • 2020-12-07 07:57

    Yes, it's called next.

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

    This outputs the following:

    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 
    
    0 讨论(0)
  • 2020-12-07 08:02

    I think it is called next.

    0 讨论(0)
提交回复
热议问题