Question

How to Skip an Iteration in Ruby .each: Using next Instead of continue

rubyloopssyntaxiteration

Question

In Ruby, how can you skip the current iteration inside an .each loop, similar to continue in other programming languages?

Short Answer

By the end of this page, you will understand how Ruby skips the current iteration of a loop using next, especially inside .each blocks. You will also see how next compares with break, redo, and loop control in other languages, along with practical examples and common mistakes.

Concept

In many programming languages, continue means: stop the current loop iteration and move to the next one.

Ruby does not use the keyword continue. Instead, Ruby uses next for this purpose.

When you are looping with .each, next immediately ends the current block execution and moves to the next element.

Example:

[1, 2, 3, 4].each do |number|
  next if number.even?
  puts number
end

Output:

1
3

Here is what happens:

  • 1 is not even, so it gets printed.
  • 2 is even, so next skips the rest of that iteration.
  • 3 is printed.
  • 4 is skipped.

This matters because skipping work is very common in real programs. You might skip:

  • invalid input rows
  • empty strings
  • users without permission
  • failed API records
  • duplicate values

Using next makes this intent clear and keeps loop logic clean.

Mental Model

Think of an .each loop like a teacher calling students one by one.

  • next means: skip this student and call the next one
  • break means: stop calling students entirely
  • normal execution means: process this student as usual

So if Ruby is in the middle of handling one item and you say next, Ruby drops the rest of that item's instructions and moves on immediately.

Take Quiz

Syntax and Examples

The basic syntax is:

collection.each do |item|
  next if condition

  # code that runs only when condition is false
end

Example 1: Skip even numbers

numbers = [1, 2, 3, 4, 5]

numbers.each do |number|
  next if number.even?
  puts number
end

Output:

1
3
5

next if number.even? means:

  • if the number is even, skip the rest of the block
  • otherwise, continue executing the block

Example 2: Skip blank names

names = ["Alice", "", "Bob", nil, "Carol"]

names.each do |name|
  next if name.nil? || name.empty?
  puts "Hello, #{name}!"
end

Output:

Hello, Alice!
Hello, Bob!
Hello, Carol!

This is a common validation pattern.

Example 3: Using next with a value

In some enumerable methods, next can return a value for that iteration.

result = [1, 2, 3].map do |n|
  next 0 if n.even?
  n * 10
end

p result

Output:

[10, 0, 30]

Inside map, next 0 means: skip the rest of the block and use 0 as that iteration's result.

Step by Step Execution

Consider this example:

numbers = [1, 2, 3]

numbers.each do |n|
  puts "Start #{n}"
  next if n == 2
  puts "End #{n}"
end

Output:

Start 1
End 1
Start 2
Start 3
End 3

Step by step:

  1. numbers contains [1, 2, 3].
  2. Ruby starts .each and takes the first value, 1.
  3. It prints Start 1.
  4. n == 2 is false, so next does not run.
  5. It prints End 1.
  6. Ruby moves to the next value, 2.
  7. It prints Start 2.
  8. n == 2 is true, so next runs.
  9. Ruby skips puts "End #{n}" for this iteration.
  10. Ruby moves to the next value, 3.
  11. It prints Start 3.
  12. n == 2 is false.
  13. It prints End 3.
  14. The loop ends.

The key idea is that next does not stop the whole loop. It only skips the rest of the current iteration.

Real World Use Cases

next is useful whenever some items in a collection should not be processed.

Filtering invalid data

rows.each do |row|
  next if row[:email].nil? || row[:email].empty?
  send_welcome_email(row[:email])
end

Ignoring admin-only restricted actions

users.each do |user|
  next unless user.admin?
  puts "Granting access to #{user.name}"
end

Skipping failed API responses

responses.each do |response|
  next unless response[:status] == 200
  process_data(response[:body])
end

Ignoring comments or blank lines in a file

File.readlines("config.txt").each do |line|
  line = line.strip
  next if line.empty? || line.start_with?("#")
  puts "Config: #{line}"
end

These examples are common in scripts, background jobs, and web applications.

Take Quiz

Real Codebase Usage

In real projects, developers often use next as a guard clause inside loops.

1. Early skip for invalid input

records.each do |record|
  next unless record.valid?
  save_record(record)
end

This keeps the main logic less nested.

2. Permission checks

tasks.each do |task|
  next unless current_user.can_edit?(task)
  update_task(task)
end

3. Skipping expensive work

images.each do |image|
  next if image.processed?
  generate_thumbnail(image)
end

4. Combining with logging

items.each do |item|
  if item.nil?
    warn "Skipping nil item"
    next
  end

  process(item)
end

5. Inside transformation methods

With methods like map, next can still be used, but you should be careful because it affects the returned values.

values = [1, 2, 3].map do |n|
  next nil if n < 2
  n * 2
end

This returns:

[nil, 4, 6]

In codebases, this pattern is useful, but developers often choose select, reject, or filter_map when they really mean filtering rather than skipping inside a transform.

Common Mistakes

Mistake 1: Using continue in Ruby

Broken code:

[1, 2, 3].each do |n|
  continue if n == 2
  puts n
end

Ruby does not have continue.

Correct code:

[1, 2, 3].each do |n|
  next if n == 2
  puts n
end

Mistake 2: Confusing next with break

Broken idea:

[1, 2, 3, 4].each do |n|
  break if n == 2
  puts n
end

Output:

1

break stops the whole loop, not just one iteration.

If you only want to skip 2, use:

[1, 2, 3, 4].each do |n|
  next if n == 2
  puts n
end

Mistake 3: Forgetting that code after next will not run

[1, 2].each do |n|
  next if n == 1
  puts "This runs only for 2"
end

Anything after next in that iteration is skipped.

Mistake 4: Using next in map without understanding returned values

result = [1, 2, 3].map do |n|
  next if n == 2
  n * 10
end

p result

Output:

[10, nil, 30]

If you expected [10, 30], this is a mistake. map always returns one result per input item.

Use select first, or use filter_map in newer Ruby versions.

Mistake 5: Writing deeply nested logic instead of skipping early

Less clear:

items.each do |item|
  if item.valid?
    if item.ready?
      process(item)
    end
  end
end

Cleaner:

items.each do |item|
  next unless item.valid?
  next unless item.ready?
  process(item)
end

This style is common and easier to read.

Comparisons

ConceptRuby keyword/methodWhat it does
Skip current iterationnextStops the current iteration and moves to the next one
Stop the loop entirelybreakEnds the whole loop immediately
Repeat current iterationredoRestarts the same iteration without moving forward
Just transform each itemmapReturns a new array with one output per input
Filter itemsselect / rejectKeeps or removes items based on a condition

next vs break

[1, 2, 3].each do |n|
  next if n == 2
  puts n
end

Output:

1
3
[1, 2, 3].each do |n|
  break if n == 2
  puts n
end

Output:

1

next vs select

Using next inside .each:

numbers.each do |n|
  next if n.even?
  puts n
end

Using select when you want filtered data:

odd_numbers = numbers.select(&:odd?)
p odd_numbers

If your goal is to skip work while iterating, use next. If your goal is to build a filtered collection, select is often better.

Take Quiz

Cheat Sheet

# Skip current iteration
next

# Skip current iteration when condition is true
next if condition

# Skip unless condition is true
next unless condition

Common patterns

items.each do |item|
  next if item.nil?
  process(item)
end
items.each do |item|
  next unless item.valid?
  process(item)
end

Loop control keywords

  • next → skip current iteration
  • break → stop the loop
  • redo → repeat current iteration

Important rule

Ruby uses next, not continue.

With map

result = [1, 2, 3].map do |n|
  next 0 if n.even?
  n * 10
end
# => [10, 0, 30]

Edge case

result = [1, 2, 3].map do |n|
  next if n == 2
  n * 10
end
# => [10, nil, 30]

If you want to remove items entirely, prefer select, reject, or filter_map.

FAQ

What is the Ruby equivalent of continue?

Ruby uses next instead of continue.

Can I use next inside .each?

Yes. next works inside .each blocks to skip the current iteration.

What is the difference between next and break in Ruby?

next skips one iteration. break stops the entire loop.

Does next work only with .each?

No. It also works in other Ruby looping constructs and enumerable blocks.

Why does map return nil when I use next?

Because map expects one output value for each input item. If next has no value, that iteration becomes nil.

Should I use next or select?

Use next when you are processing items in a loop and want to skip some of them. Use select when you want to build a filtered array.

Is continue valid Ruby syntax?

No. Ruby does not have a continue keyword.

Take Quiz

Mini Project

Description

Build a small Ruby script that processes a list of usernames and skips invalid entries. This demonstrates how next helps ignore bad data while continuing to process the rest of the collection.

Goal

Create a script that prints greetings only for valid usernames.

Requirements

  • Store several usernames in an array, including empty strings and nil values.
  • Loop through the array with .each.
  • Skip invalid usernames using next.
  • Print a greeting for each valid username.
Take Quiz

Keep learning

Related questions

View more