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
endThis 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, 6The 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
EasyRead two integers from input:
- A
startnumber - An
endnumber
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
10If the inputs are 5 and 9, the output should be:
5
7
8Cheat 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, 5Use 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, 6next 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 3This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 42Variables and Data Types
Numbers and VariablesString Data TypeBoolean Data TypeSymbol Data TypeChecking Data TypesNaming ConventionsRecap - Variable Creation8Loops
For Loop with RangesWhile LoopBreakNextRecap - FactorialTimes LoopUntil LoopNested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators6Basic IO
Output with putsOutput with print and pOutput With VariablesInput with getsChomp MethodType ConversionRecap - Age CalculatorRecap - True or False