Ruby break & next
Control loop execution flow
🛑 What are break & next?
Break and next are control flow keywords that change how loops execute. Break exits the loop entirely, while next skips to the next iteration. They give you precise control over loop behavior.
# break example
5.times do |i|
break if i == 3
puts i
end
# Outputs: 0, 1, 2
Output:
0 1 2
break vs next
break
Exits the loop completely
5.times do |i|
break if i == 2
puts i
end
# Outputs: 0, 1
next
Skips to next iteration
5.times do |i|
next if i == 2
puts i
end
# Outputs: 0, 1, 3, 4
Conditional break
Break when condition is met
loop do
num = rand(10)
puts num
break if num > 7
end
Conditional next
Skip when condition is met
(1..5).each do |n|
next if n.even?
puts n
end
# Outputs: 1, 3, 5
🔹 Using break
The break keyword immediately exits the loop, stopping all further iterations. It's useful when you've found what you're looking for or met a stopping condition.
# Stop when target is found
numbers = [1, 5, 3, 8, 2, 9]
numbers.each do |num|
puts "Checking: #{num}"
if num == 8
puts "Found 8! Stopping search."
break
end
end
# Break with while loop
count = 0
while true
count += 1
puts count
break if count >= 3
end
puts "Loop ended"
Output:
Checking: 1 Checking: 5 Checking: 3 Checking: 8 Found 8! Stopping search. 1 2 3 Loop ended
🔹 Using next
The next keyword skips the rest of the current iteration and moves to the next one. It's perfect for filtering or skipping unwanted values.
# Skip even numbers
(1..6).each do |num|
next if num.even?
puts "Odd number: #{num}"
end
# Skip negative values
values = [5, -2, 8, -1, 3]
values.each do |val|
next if val < 0
puts "Positive: #{val}"
end
Output:
Odd number: 1 Odd number: 3 Odd number: 5 Positive: 5 Positive: 8 Positive: 3
🔹 break with Return Values
In Ruby, break can return a value from the loop. This value becomes the result of the entire loop expression.
# break returns a value
result = [1, 2, 3, 4, 5].each do |num|
break "Found it!" if num == 3
end
puts result
# Find first even number
first_even = [1, 3, 5, 6, 7, 8].each do |num|
break num if num.even?
end
puts "First even number: #{first_even}"
# Without break, returns the array
no_break = [1, 2, 3].each do |num|
puts num
end
puts "Result: #{no_break}"
Output:
Found it! First even number: 6 1 2 3 Result: [1, 2, 3]
🔹 Practical Examples
Here are real-world scenarios where break and next are commonly used:
# Search for a word
words = ["apple", "banana", "cherry", "date"]
search = "cherry"
found = false
words.each do |word|
if word == search
puts "Found: #{word}"
found = true
break
end
end
puts "Not found" unless found
# Process only valid data
data = [10, -5, 20, 0, 15, -3, 25]
sum = 0
data.each do |num|
next if num <= 0 # Skip non-positive numbers
sum += num
puts "Added #{num}, sum is now #{sum}"
end
puts "Total: #{sum}"
Output:
Found: cherry Added 10, sum is now 10 Added 20, sum is now 30 Added 15, sum is now 45 Added 25, sum is now 70 Total: 70
🔹 break and next in Nested Loops
When using break or next in nested loops, they only affect the innermost loop they're in. To break out of outer loops, you need different strategies.
# break only exits inner loop
(1..3).each do |i|
puts "Outer: #{i}"
(1..3).each do |j|
puts " Inner: #{j}"
break if j == 2 # Only breaks inner loop
end
end
puts "\n---\n"
# next only skips inner iteration
(1..3).each do |i|
(1..3).each do |j|
next if j == 2 # Skips when j is 2
puts "i=#{i}, j=#{j}"
end
end
Output:
Outer: 1 Inner: 1 Inner: 2 Outer: 2 Inner: 1 Inner: 2 Outer: 3 Inner: 1 Inner: 2 --- i=1, j=1 i=1, j=3 i=2, j=1 i=2, j=3 i=3, j=1 i=3, j=3
🔹 Common Patterns
Here are some common patterns using break and next that you'll see frequently in Ruby code:
# Pattern 1: Early exit on condition
def find_first_negative(numbers)
numbers.each do |num|
return num if num < 0
end
nil
end
puts find_first_negative([5, 3, -2, 8])
# Pattern 2: Skip invalid items
items = ["apple", "", "banana", nil, "cherry"]
items.each do |item|
next if item.nil? || item.empty?
puts "Processing: #{item}"
end
# Pattern 3: Limit iterations
count = 0
[1, 2, 3, 4, 5, 6, 7, 8].each do |num|
break if count >= 3
puts num
count += 1
end
Output:
-2 Processing: apple Processing: banana Processing: cherry 1 2 3
🔹 Best Practices
Follow these guidelines when using break and next:
When to Use break:
- Found what you need: Stop searching once target is found
- Error conditions: Exit loop when something goes wrong
- Limit reached: Stop after processing enough items
- Infinite loops: Essential for exiting loop blocks
When to Use next:
- Skip invalid data: Ignore nil, empty, or invalid values
- Filter conditions: Process only items meeting criteria
- Avoid nesting: Reduce if-else nesting by skipping early
- Conditional processing: Handle special cases differently