Kernel#loop
loop { block } Returns:
nil or block's last expression · Updated March 13, 2026 · Kernel Methods iteration loops infinite control-flow
loop is a built-in Kernel method that executes a block indefinitely until explicitly terminated with break. It’s useful when you need an infinite loop and want full control over when to exit.
Syntax
loop do
# code to execute repeatedly
end
Parameters
loop takes no parameters. It accepts a block that will be executed repeatedly.
Examples
Basic infinite loop
counter = 0
loop do
counter += 1
puts counter
break if counter >= 5
end
# Output:
# 1
# 2
# 3
# 4
# 5
Using next to skip iterations
counter = 0
loop do
counter += 1
next if counter.odd?
puts counter
break if counter >= 10
end
# Output:
# 2
# 4
# 6
# 8
# 10
Raising and rescuing to simulate retry logic
attempts = 0
loop do
attempts += 1
begin
# Simulate a flaky operation
result = rand(1..10)
if result < 7
raise "Failed attempt"
end
puts "Success on attempt #{attempts}!"
break
rescue => e
puts "Attempt #{attempts} failed: #{e.message}"
raise if attempts >= 3
end
end
Common Patterns
Generating sequences
# Generate Fibonacci numbers
a, b = 0, 1
loop do
puts a
a, b = b, a + b
break if a > 1000
end
Waiting for a condition
require 'timeout'
status = :pending
loop do
# In real code, this would check an external resource
status = :ready if rand > 0.7
break :done if status == :ready
end
Reading from a stream until exhausted
# Read lines until EOF
loop do
line = gets
break if line.nil?
puts line.upcase
end
Errors
- LocalJumpError: If
breakis called outside a block, Ruby raises aLocalJumpError. - ArgumentError:
loopdoes not accept arguments. Passing arguments will raise anArgumentError.