Question
How to Skip an Iteration in Ruby .each: Using next Instead of continue
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:
1is not even, so it gets printed.2is even, sonextskips the rest of that iteration.3is printed.4is 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.
nextmeans: skip this student and call the next onebreakmeans: 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.
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:
numberscontains[1, 2, 3].- Ruby starts
.eachand takes the first value,1. - It prints
Start 1. n == 2is false, sonextdoes not run.- It prints
End 1. - Ruby moves to the next value,
2. - It prints
Start 2. n == 2is true, sonextruns.- Ruby skips
puts "End #{n}"for this iteration. - Ruby moves to the next value,
3. - It prints
Start 3. n == 2is false.- It prints
End 3. - 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.
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
| Concept | Ruby keyword/method | What it does |
|---|---|---|
| Skip current iteration | next | Stops the current iteration and moves to the next one |
| Stop the loop entirely | break | Ends the whole loop immediately |
| Repeat current iteration | redo | Restarts the same iteration without moving forward |
| Just transform each item | map | Returns a new array with one output per input |
| Filter items | select / reject | Keeps 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.
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 iterationbreak→ stop the loopredo→ 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.
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
nilvalues. - Loop through the array with
.each. - Skip invalid usernames using
next. - Print a greeting for each valid username.
Keep learning
Related questions
Add a Default Value to an Existing Column in a Rails Migration
Learn how to add or change a default value on an existing database column using Rails Active Record migrations safely.
Calling a Class Method from an Instance in Ruby
Learn how to call a class method from an instance in Ruby using self.class, with examples, pitfalls, and practical usage patterns.
Calling an Overridden Monkey-Patched Method in Ruby
Learn how to call the original method when monkey patching in Ruby, including alias_method patterns, examples, pitfalls, and practical usage.