Menu
Coddy logo textTech

Next

Part of the Fundamentals section of Coddy's Ruby journey — lesson 42 of 88.

While break exits a loop entirely, sometimes you just want to skip the current iteration and move on to the next one. The next keyword does exactly that.

When Ruby encounters next, it immediately jumps to the next iteration of the loop, skipping any remaining code in the current iteration:

for i in 1..5
  if i == 3
    next
  end
  puts i
end

This outputs 1, 2, 4, 5. When i equals 3, the next keyword skips the puts statement and moves directly to the next iteration where i becomes 4.

A common use case is filtering out unwanted values. For example, printing only even numbers:

for num in 1..6
  if num % 2 != 0
    next
  end
  puts num
end
# Outputs: 2, 4, 6

The odd numbers are skipped, and only even numbers get printed. Think of next as saying "skip this one and continue" while break says "stop everything."

challenge icon

Challenge

Easy

Read two integers from input:

  1. A start number
  2. An end number

Loop through numbers from start to end. Print only the numbers that are not divisible by 3. Use next to skip numbers that are divisible by 3.

Each number should be printed on its own line.

For example, if the inputs are 1 and 10, the output should be:

1
2
4
5
7
8
10

If the inputs are 5 and 9, the output should be:

5
7
8

Cheat sheet

The next keyword skips the current iteration of a loop and moves to the next one:

for i in 1..5
  if i == 3
    next
  end
  puts i
end
# Outputs: 1, 2, 4, 5

Use next to filter values. For example, printing only even numbers:

for num in 1..6
  if num % 2 != 0
    next
  end
  puts num
end
# Outputs: 2, 4, 6

next skips the current iteration and continues the loop, while break exits the loop entirely.

Try it yourself

# Read input
start = gets.chomp.to_i
end_num = gets.chomp.to_i

# TODO: Write your code below
# Loop through numbers from start to end_num
# Use next to skip numbers divisible by 3
# Print numbers that are NOT divisible by 3
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals