0
0
RubyHow-ToBeginner · 3 min read

How to Use break in Ruby: Simple Guide with Examples

In Ruby, use the break keyword inside loops to immediately stop the loop and exit it. This helps you end a loop early when a condition is met.
📐

Syntax

The break keyword is used inside loops like while, for, or each to stop the loop immediately.

Optionally, you can provide a value with break which becomes the result of the loop.

ruby
loop do
  break
end

# or with a value
result = loop do
  break 42
end
💻

Example

This example shows a loop that counts from 1 to 5 but stops early when the count reaches 3 using break.

ruby
count = 1
loop do
  puts count
  break if count == 3
  count += 1
end
Output
1 2 3
⚠️

Common Pitfalls

One common mistake is using break outside a loop, which causes an error. Another is forgetting that break stops only the innermost loop.

Also, using break in methods without loops does not exit the method.

ruby
def wrong_break
  break  # Error: break used outside loop
end

# Correct usage inside a loop:
3.times do |i|
  break if i == 1
  puts i
end
Output
0
📊

Quick Reference

break stops the current loop immediately.

Use break with a value to return that value from the loop.

Works with while, until, for, loop, and iterator methods like each.

Key Takeaways

Use break inside loops to exit early when a condition is met.
break can return a value from the loop if needed.
Do not use break outside loops; it causes errors.
break only stops the innermost loop it is in.
Common loops that support break include while, for, and loop.