Question

Ruby Loop Control: The Equivalent of continue in Ruby

rubykeywordcontinue

Question

In C and many other programming languages, the continue keyword is used inside a loop to skip the rest of the current iteration and move directly to the next one. Is there an equivalent to continue in Ruby?

Short Answer

By the end of this page, you will understand that Ruby uses next as the equivalent of continue. You will learn how next behaves in different kinds of loops, how it helps skip unwanted work, and how to use it clearly in real Ruby code.

Concept

In Ruby, the equivalent of continue is next.

When Ruby reaches next inside a loop or block iteration, it stops executing the rest of the current iteration and immediately moves to the next one.

This matters because loops often process many items, and sometimes you want to skip certain values:

  • ignore invalid input
  • skip empty strings
  • avoid unnecessary work
  • handle special cases early

Ruby does not use the keyword continue for this purpose. Instead, it uses a small set of loop-control keywords:

  • next → skip to the next iteration
  • break → leave the loop completely
  • redo → repeat the current iteration without moving on

A simple 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 is printed
  • 2 is even, so next skips the puts
  • 3 is not even, so it is printed
  • 4 is even, so it is skipped

In real programming, this pattern is very common because it keeps code simpler. Instead of wrapping everything in a large if block, you can skip unwanted cases early and keep the main logic easier to read.

Mental Model

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

For each student, the teacher normally does the full routine:

  1. call the name
  2. ask a question
  3. record the answer

But sometimes the student is absent. In that case, the teacher says, “skip this one, go to the next student.”

That is what next does in Ruby.

  • next = skip this turn and move on
  • break = stop calling students entirely
  • redo = repeat this same student's turn again

So if continue in another language means “skip the rest of this loop cycle,” Ruby's next means the same idea.

Take Quiz

Syntax and Examples

Basic syntax

next

It is usually used inside a loop or iterator block:

array.each do |item|
  next if some_condition
  # code here runs only when the condition is false
end

Example 1: Skip even numbers

(1..5).each do |number|
  next if number.even?
  puts number
end

Output:

1
3
5

Explanation:

  • next if number.even? skips 2 and 4
  • only odd numbers reach puts

Example 2: Skip blank strings

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

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

Output:

Hello, Alice!
Hello, Bob!
Hello, Charlie!

This is useful when cleaning or validating data before processing it.

Example 3: Using next in a while loop

i = 0

while i < 5
  i += 1
  next if i == 3
  puts i
end

Output:

1
2
4
5

This skips printing 3 and continues with the next loop iteration.

Example 4: next with a value in block-based methods

In some Ruby iterators, next can return a value for the current block iteration.

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

p result

Output:

[10, 0, 30, 0]

Here:

  • even numbers return 0 for that iteration
  • odd numbers return n * 10

This is especially useful with methods like map.

Step by Step Execution

Consider this code:

numbers = [1, 2, 3, 4]

numbers.each do |n|
  next if n > 2
  puts "Processing #{n}"
end

Step-by-step trace

Iteration 1

  • n is 1
  • n > 2 is false
  • next does not run
  • puts "Processing 1" runs

Iteration 2

  • n is 2
  • n > 2 is false
  • next does not run
  • puts "Processing 2" runs

Iteration 3

  • n is 3
  • n > 2 is true
  • next runs
  • Ruby skips the rest of this iteration
  • puts does not run

Iteration 4

  • n is 4
  • n > 2 is true
  • next runs
  • Ruby skips the rest of this iteration
  • puts does not run

Output:

Processing 1
Processing 2

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

Real World Use Cases

next is useful whenever some items should be ignored during loop processing.

1. Skipping invalid records

users.each do |user|
  next unless user[:email]
  send_email(user)
end

Only users with an email address are processed.

2. Ignoring comment or empty lines in files

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

Useful in configuration files, import scripts, and CLI tools.

3. Skipping failed API items

responses.each do |response|
  next unless response[:success]
  save_data(response[:data])
end

This avoids running code on bad responses.

4. Filtering data during iteration

orders.each do |order|
  next if order.cancelled?
  process_order(order)
end

Only active orders are processed.

5. Avoiding unnecessary computation

numbers.each do |n|
  next if n.zero?
  puts 100 / n
end

This can prevent errors and wasted work.

Take Quiz

Real Codebase Usage

In real Ruby codebases, next is often used to keep loops flatter and easier to read.

Guard-style skipping

Developers often skip invalid cases early:

rows.each do |row|
  next if row.nil?
  next if row[:status] != "active"

  process(row)
end

This avoids deeply nested if statements.

Validation before processing

params.each do |key, value|
  next if value.nil?
  config[key] = value
end

Only valid values are copied.

Working with enumerables

Ruby developers often combine next with methods like each, map, and select.

slugs = titles.map do |title|
  next "untitled" if title.nil? || title.empty?
  title.downcase.gsub(" ", "-")
end

Error-resistant loops

files.each do |file|
  next unless File.exist?(file)
  process_file(file)
end

This pattern reduces crashes from bad input.

Readable early exits inside blocks

items.each do |item|
  next unless allowed?(item)
  next if archived?(item)

  publish(item)
end

This reads like a sequence of simple rules.

In production code, next is best when the loop should continue, but a specific item should be ignored.

Common Mistakes

1. Using continue instead of next

Ruby does not have a continue keyword.

Broken code:

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

Correct code:

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

2. Confusing next with break

  • next skips one iteration
  • break stops the loop entirely
[1, 2, 3, 4].each do |n|
  break if n == 3
  puts n
end

Output:

1
2

If you wanted to skip only 3, use next instead.

3. Forgetting to update loop variables in while loops

This can create infinite loops.

Broken code:

i = 0
while i < 5
  next if i == 2
  i += 1
end

Why it breaks:

  • when i becomes 2, next runs immediately
  • i += 1 is skipped
  • i stays 2 forever

Correct code:

i = 0
while i < 5
  i += 1
  next if i == 2
  puts i
end

4. Using next outside a loop or block

next only makes sense in an iteration context.

Broken idea:

next

Use it only inside loops, iterator blocks, or similar control-flow contexts.

5. Overusing next when select or reject is clearer

Sometimes transformation code becomes cleaner with higher-level enumerable methods.

Less clear:

result = []
numbers.each do |n|
  next if n.even?
  result << n
end

Clearer:

result = numbers.reject(&:even?)

Use next when you truly need loop control, not when a collection method expresses the intent better.

Comparisons

ConceptWhat it doesRuby keyword/methodWhen to use
Skip current iterationIgnore the rest of this loop cycle and move onnextWhen one item should be skipped
Stop loop entirelyExit the loop nowbreakWhen no more iterations are needed
Repeat same iterationStart the current iteration againredoRare cases where the same item must be retried
Filter collectionKeep only matching itemsselect, rejectWhen building a filtered result is the real goal

next vs break

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

Output:

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

Output:

1

next vs select

Using next:

result = []
[1, 2, 3, 4].each do |n|
  next if n.even?
  result << n
end
p result

Using select:

result = [1, 2, 3, 4].select { |n| n.odd? }
p result

Both work, but select is often better when the main goal is filtering.

Take Quiz

Cheat Sheet

# Ruby equivalent of continue
next

Common patterns

next if condition
next unless condition

Example with each

items.each do |item|
  next if item.nil?
  puts item
end

Example with while

i = 0
while i < 5
  i += 1
  next if i == 3
  puts i
end

Related loop control keywords

break  # exit the loop completely
next   # skip to the next iteration
redo   # repeat the current iteration

Rules to remember

  • Ruby uses next, not continue
  • next skips only the current iteration
  • break stops the whole loop
  • In while loops, update counters before next when needed
  • In methods like map, next value can provide the value for that iteration

Quick example with map

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

FAQ

Is there a continue keyword in Ruby?

No. Ruby uses next instead of continue.

What is the difference between next and break in Ruby?

next skips the current iteration and continues the loop. break exits the loop completely.

Can I use next inside each blocks in Ruby?

Yes. That is one of the most common places to use it.

Can next be used in a while loop?

Yes. It works in while, until, and iterator blocks. Be careful to update loop variables correctly.

Does next return a value in Ruby?

In iterator methods like map, next can provide the value for that block iteration.

When should I use select instead of next?

Use select when your main goal is to filter a collection. Use next when you are controlling flow inside a loop.

Is redo the same as next in Ruby?

No. next moves to the next iteration. redo repeats the current iteration.

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 you ignore bad data while continuing to handle the rest of the list.

Goal

Create a script that prints only valid usernames and skips blank or blocked entries using next.

Requirements

  • Create an array of usernames that includes valid names, empty strings, and blocked names.
  • Loop through the usernames with Ruby iteration.
  • Use next to skip empty usernames.
  • Use next to skip blocked usernames.
  • Print a greeting for each valid username.
Take Quiz

Keep learning

Related questions

View more