Mark Szymanski
Mark Szymanski

Reputation: 58050

Equivalent of "continue" in Ruby

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?

Upvotes: 762

Views: 325129

Answers (9)

Chris
Chris

Reputation: 36451

Late addition: you may not want to use next at all, but rather reject any values less than 2 and then print the rest.

By using #lazy we avoid the creation of an intermediate array at the .reject { |x| x < 2 } stage. Not very meaningful for such a small sample size, but if we ran this on (0..10_000_000) for instance, it would be much more meaningful.

(0..5).lazy.reject { |x|
    x < 2
}.each { |x|
    puts x
}

Upvotes: 0

eQ19
eQ19

Reputation: 10691

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

Upvotes: 2

Rakesh Kumar
Rakesh Kumar

Reputation: 19

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

Upvotes: 1

sberkley
sberkley

Reputation: 1208

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

Upvotes: 110

Ian Purton
Ian Purton

Reputation: 15891

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 

Upvotes: 1085

19WAS85
19WAS85

Reputation: 2863

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

Upvotes: 34

Nick Moore
Nick Moore

Reputation: 15847

next

also, look at redo which redoes the current iteration.

Upvotes: 128

idursun
idursun

Reputation: 6335

I think it is called next.

Upvotes: 10

sepp2k
sepp2k

Reputation: 370092

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.

Upvotes: 44

Related Questions