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?
-
5continue doesn't "restart" the loops but jumps to the next iteration of the loop. – Matt Crinklaw-Vogt Oct 24 '10 at 19:54
-
1@mlaw: I edited my question accordingly to prevent future confusion. – Mark Szymanski Oct 24 '10 at 21:19
-
8@dbr the duplicate you've found was asked after this one. – Droogans Oct 22 '13 at 21:52
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
-
14This is how I remember--Ruby respects Perl (
next
) above C (continue
) – Colonel Panic Jul 5 '12 at 18:43 -
ProTip: Careful using it with
and
likeputs "Skipping" and next if i < 2
becauseputs
returnsnil
, which is "falsey", and sonext
won't get called. – Joshua Pinter Oct 26 '20 at 20:05
next
also, look at redo
which redoes the current iteration.
-
43
-
1Ruby borrowed much from Perl, including Perl's
redo
command (or its essence, anyway). For Ruby's interpretation, search for "redo" within this page. – MarkDBlackwell Mar 30 '19 at 14:32
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
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.
Ruby has two other loop/iteration control keywords: redo
and retry
.
Read more about them, and the difference between them, at Ruby QuickTips.
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