Ruby example

How to skip to the next iteration in Ruby

8 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Use next, Ruby's continue: items.each { |x| next if x.nil?; puts x } skips the rest of the block and moves on to the next element. It works in each, while, times and every other loop or block. Use break to stop the loop altogether, and catch/throw to leave several nested loops at once.

Ruby has no continue keyword. Most Ruby loops are blocks passed to methods like each, and the block keywords are next (end this pass and go to the next one), break (stop the loop) and return (leave the method the block was written in). The sections below cover next as a guard clause, what next with a value puts into map and select, break and the value it returns, how return behaves in a block and in a lambda, breaking out of nested loops with catch and throw, and Ruby's do-while loop, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1next: skip the rest of this passRecommended

next ends the current pass through the block (or the loop body) and moves on to the next element, exactly like continue in Python, Java or JavaScript. It is almost always written with a modifier: next if … or next unless …. Used at the top of the block as a guard clause, it skips the elements you don't want and keeps the main work unindented, instead of wrapping everything in an if. The same keyword works in while, until, times, loop and any method that takes a block.

next.rb
# next skips the rest of this pass and moves on
(1..6).each do |n|
  next if n.even?
  puts "odd: #{n}"
end

# It works the same in while, until, times and loop
seen = []
i = 0
while i < 5
  i += 1
  next if i == 3
  seen << i
end
p seen

3.times do |t|
  next unless t.positive?
  puts "times: #{t}"
end

# Guard clauses keep the main work unindented
lines = ["# comment", "", "name = Ann", "  ", "age = 31"]
lines.each do |line|
  next if line.strip.empty?
  next if line.start_with?("#")
  key, value = line.split(" = ")
  puts "#{key} -> #{value}"
end

Output

The first loop prints odd: 1, odd: 3 and odd: 5; the even numbers reach next and never get to puts. In the while loop, i += 1 comes before next, so 3 is skipped and the result is [1, 2, 4, 5]; put the increment after next and the loop never ends. The last loop drops the blank line, the whitespace-only line and the comment, and prints only name -> Ann and age -> 31. Typing continue out of habit raises undefined local variable or method 'continue' for main.

2next with a value in map, select and reduce

A block returns a value to the method that called it, and next can supply that value early: next value ends the pass and hands value back. In each the value is ignored, but in map it becomes that element of the result, and a bare next puts nil there. So next in map does not drop an element; to skip elements while transforming, use filter_map (Ruby 2.7 and later) or map followed by compact. In select, next false rejects the element.

next_with_value.rb
words = ["apple", "", "banana", nil, "cherry"]

# In map, next's value becomes that element of the result
labels = words.map do |w|
  next "(blank)" if w.nil? || w.empty?
  w.upcase
end
p labels

# A bare next puts nil there; it does not drop the element
with_nils = words.map do |w|
  next if w.nil? || w.empty?
  w.upcase
end
p with_nils

# To skip elements while mapping, use filter_map
p words.filter_map { |w| w.upcase unless w.nil? || w.empty? }

# The older spelling: map, then remove what you don't want
p words.map { |w| w&.upcase }.compact.reject(&:empty?)

# In select, next false rejects the element
picked = (1..10).select do |n|
  next false if n < 4
  n.odd?
end
p picked

# In reduce, next must pass the running total along
p [1, 2, 3, 4].reduce(0) { |sum, n| next sum if n == 2; sum + n }

Output

The second line is the common surprise: ["APPLE", nil, "BANANA", nil, "CHERRY"] still has five elements, with nil where next skipped. filter_map keeps only the truthy results and gives ["APPLE", "BANANA", "CHERRY"] in one pass. In reduce (also named inject), the block's value becomes the next running total, so the skip must be next sum: the result is 8, the sum without the 2. A bare next there makes the total nil, and the next pass fails with undefined method '+' for nil.

3break: stop the loop, optionally with a value

break stops the loop at once and continues after it. In a block it ends the whole method call, so break inside each also stops each. Every Ruby loop is an expression, and break value makes value the result of the call: each normally returns the array it walked, while returns nil, and loop returns whatever you break with. That makes loop do … break result if … end a compact retry pattern. When you are searching for one element, find already does the break for you.

break_value.rb
numbers = [5, 8, 13, 21, 34]

# break leaves the loop at once
numbers.each do |n|
  break if n > 15
  puts "checked #{n}"
end

# each returns its receiver; break value returns value instead
result = numbers.each do |n|
  break n if n > 15
end
p result

# Without a break, each returns the array itself
p [1, 2].each { |n| n * 100 }

# A bare break makes the result nil
p [1, 2, 3].each { |n| break if n == 2 }

# loop do ... end hands back the break value too
attempt = 0
answer = loop do
  attempt += 1
  break "ok after #{attempt} tries" if attempt == 3
end
puts answer

# while gives nil unless you break with a value
p(while true do break end)
p(while true do break 42 end)

# For "the first one that matches", find does the break for you
p numbers.find { |n| n > 15 }

Output

The loop checks 5, 8 and 13, then stops at 21 without looking at 34. break n makes the each call return 21, while an each that runs to the end returns its array ([1, 2], not the block's values; that is what map is for). The retry loop prints ok after 3 tries. The last line gets the same 21 from find, which is the clearer way to write the second loop.

4return in a block vs in a lambda

return inside a block does not end the block: it returns from the method the block was written in, ending the loop along the way. That makes an early exit from a search method short, as in first_negative below. A lambda is different: there return behaves like it does in a method and leaves only the lambda. A proc follows the block rule, so if it outlives the method that made it, its return has nowhere to go and raises LocalJumpError. To leave only the block, use next; to stop only the loop, use break.

return_from_block.rb
# return inside a block returns from the enclosing method
def first_negative(numbers)
  numbers.each do |n|
    return n if n.negative?
  end
  nil
end

p first_negative([4, -2, 7, -9])
p first_negative([1, 2])

# next leaves the block, break leaves the call, return the method
def demo
  a = [1, 2, 3].map { |n| next n * 10 if n.odd?; n }
  b = [1, 2, 3].each { |n| break n * 100 if n == 2 }
  p a, b
  [1, 2, 3].each { |n| return "left demo at #{n}" if n == 3 }
  "never gets here"
end
p demo

# In a lambda, return leaves only the lambda
check = ->(n) { return "negative" if n.negative?; "fine" }
p [3, -1].map { |n| check.call(n) }

# A proc's return belongs to the method that made it
def make_proc
  proc { return 1 }
end

begin
  make_proc.call
rescue LocalJumpError => e
  puts "#{e.class}: #{e.message}"
end

Output

first_negative returns -2 as soon as it sees it and nil when the loop ends without a match. In demo, next sets one element of map's result ([10, 2, 30]), break sets the value of the each call (200), and return leaves the whole method, so "never gets here" is never reached. The lambda returns "negative" to map without stopping it. The proc made inside make_proc tries to return from a method that has already finished, hence LocalJumpError: unexpected return.

5Break out of nested loops: catch and throw

break only leaves the innermost loop, and Ruby has no labeled break like Java or Kotlin. To leave several loops at once, wrap them in catch(:tag) do … end and call throw :tag, value from anywhere inside: Ruby unwinds every loop up to the matching catch, which returns the thrown value (or the block's last value when nothing is thrown). Despite the names, this is not exception handling; Ruby's exceptions use raise and rescue. Often the clearest option is to move the loops into a method and return from it.

nested_loops.rb
grid = [
  [3, 8, 1],
  [9, 4, 7],
  [2, 6, 5]
]

# throw jumps out of every loop up to the matching catch
found = catch(:found) do
  grid.each_with_index do |row, r|
    row.each_with_index do |value, c|
      puts "looking at #{value}"
      throw :found, [r, c] if value > 8
    end
  end
  nil
end
p found

# When nothing is thrown, catch returns the block's last value
missing = catch(:found) do
  grid.each { |row| row.each { |v| throw :found, v if v > 100 } }
  :not_found
end
p missing

# break alone only leaves the inner loop
kept = []
grid.each do |row|
  row.each do |value|
    break if value == 4
    kept << value
  end
end
p kept

# Often a method with return is clearer
def position_of(grid, target)
  grid.each_with_index do |row, r|
    c = row.index(target)
    return [r, c] if c
  end
  nil
end

p position_of(grid, 6)
p position_of(grid, 42)

Output

The search looks at four values and stops at 9, row 1, column 0: catch returns [1, 0] and no more values are visited. With nothing thrown, the second catch returns :not_found. The plain break version only cuts row 1 short at 4 (dropping 4 and 7) and carries on with row 2, so kept is [3, 8, 1, 9, 2, 6, 5]. position_of does the same search as the first catch with an ordinary return. A throw with no matching catch raises UncaughtThrowError: uncaught throw :nope (for a tag named :nope).

6A do-while loop: loop with break if

Ruby has no do … while statement, but begin … end while condition behaves like one: the body runs once before the test. It is a special case, since a while modifier on a single statement tests first, and Matz, Ruby's creator, has said he regrets adding it and would rather people not use it. The recommended form is loop do … end with break if at the point where you want the test, which also lets you test in the middle of the body. until is while with the condition negated, and loop ends quietly when an external enumerator runs out.

do_while.rb
# begin ... end while: the body runs once before the test
n = 10
begin
  puts "begin/while ran with n = #{n}"
  n += 1
end while n < 5

# A while modifier on one statement tests first: never runs
m = 10
puts "never printed" while m < 5

# The recommended style: loop do, then break if
count = 0
loop do
  count += 1
  puts "loop ran, count = #{count}"
  break if count >= 2
end

# until is while with the test negated
tries = 0
begin
  tries += 1
end until tries == 3
p tries

# loop stops by itself when an enumerator runs out
colors = %w[red green].each
loop do
  puts colors.next
end
puts "after loop"

Output

begin/while ran with n = 10 prints once even though 10 < 5 is false, while the one-line while modifier prints nothing. The loop version runs twice and stops at break if count >= 2, and the begin … end until form leaves tries at 3. In the last loop, colors.next raises StopIteration after green; loop catches it and ends, so after loop prints with no error.

7Which should you use?

KeywordLeavesValue it givesBest for
nextThis pass onlynext x: this element in mapSkipping an element (continue)
breakThe loop or callbreak x: the whole callStopping early, returning a result
returnThe enclosing methodThe method's resultEarly exit from a search method
catch / throwEvery loop up to catchthrow :tag, x: the catchNested loops with no method to return from
filter_mapNot a keywordOnly truthy resultsSkipping while transforming
loop + break ifThe loopbreak x: the loopdo-while, retries
begin … end whileThe loopnilOld code; prefer loop + break if

Frequently asked questions

What is the Ruby equivalent of continue?

It is next. Write next if condition inside each, while, times or any block to skip the rest of the current pass. continue is not a Ruby keyword: Ruby reads it as a method call and raises NameError: undefined local variable or method 'continue' for main.

How do I skip the first few elements in each?

Drop them before looping: items.drop(2).each { … } skips the first two ([10, 20, 30, 40].drop(2) is [30, 40]). If you also need the original positions, use each_with_index and next if i < 2. drop_while { … } skips elements until a condition becomes false.

What does redo do?

redo restarts the current pass of the block with the same element, without checking the loop condition or moving on. It is rare in real code and easy to turn into an endless loop, so guard it with a counter. For retrying failed work, retry in a rescue clause or loop do … break if ok end is usually clearer.

Why does next inside reduce give a NoMethodError?

In reduce (or inject), the value of each pass becomes the running total for the next one. A bare next hands back nil, so the following pass calls a method on nil and fails with undefined method '+' for nil. Write next sum if … to pass the total along unchanged.

Can I use return inside each at the top level of a script?

Yes, but it ends the whole script, quietly and with exit status 0, because at the top level there is no method to return from. Use break to stop only the loop, or put the loop in a method so return has a method to leave.

Does Ruby have labeled break like Java?

No. break and next always apply to the innermost loop or block. To leave several nested loops, wrap them in catch(:done) do … end and call throw :done, value inside, or move the loops into a method and return from it.

Run it yourself

Open any of these in the full Ruby editor to tweak, run and share.

Ruby playground