747

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 this continue keyword in Ruby?

Jasper
  • 2,166
  • 4
  • 30
  • 50
Mark Szymanski
  • 56,590
  • 24
  • 70
  • 87

8 Answers8

1064

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 
Seth
  • 10,198
  • 10
  • 45
  • 68
Ian Purton
  • 15,331
  • 2
  • 27
  • 26
125

next

also, look at redo which redoes the current iteration.

Nick Moore
  • 15,547
  • 6
  • 61
  • 83
  • 52
    ... cause ruby is rad like that. – matt walters Feb 08 '13 at 22:36
  • 2
    Ruby borrowed much from Perl, including Perl's [`redo`](https://perldoc.perl.org/functions/redo.html) command (or its essence, anyway). For Ruby's interpretation, search for "redo" within [this page](https://ruby-doc.org/core-2.2.5/doc/syntax/control_expressions_rdoc.html). – MarkDBlackwell Mar 30 '19 at 14:32
108

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
Magne
  • 16,401
  • 10
  • 68
  • 88
sberkley
  • 1,188
  • 1
  • 8
  • 4
44

Inside for-loops and iterator methods like each and map the next keyword in ruby will have the effect of jumping to the next iteration of the loop (same as continue in C).

However what it actually does is just to return from the current block. So you can use it with any method that takes a block - even if it has nothing to do with iteration.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
34

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

Alan H.
  • 16,219
  • 17
  • 80
  • 113
19WAS85
  • 2,853
  • 1
  • 20
  • 19
10

I think it is called next.

idursun
  • 6,261
  • 1
  • 37
  • 51
1

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

Mebin Joe
  • 2,172
  • 4
  • 16
  • 22
1

Use may use next conditionally

before = 0
"0;1;2;3".split(";").each.with_index do |now, i|
    next if i < 1
    puts "before it was #{before}, now it is #{now}"
    before = now
end

output:

before it was 0, now it is 1
before it was 1, now it is 2
before it was 2, now it is 3
eQ19
  • 9,880
  • 3
  • 65
  • 77