LocalJumpError
RubyERRORNotableControl Flow
Invalid use of break, return, or next outside block
Quick Answer
Use lambda instead of Proc for stored callables, or rescue LocalJumpError when iterating with optional blocks.
What this means
Raised when a break, return, or next is used in a context where it is not valid — most commonly when a stored Proc is called after its enclosing method has already returned.
Why it happens
- 1Calling a Proc (stored from a block) after the enclosing method has returned
- 2Using break inside a Proc that is not being called from inside an iterator
Fix
Use lambda for stored callables
Use lambda for stored callables
callback = lambda { |x| return x * 2 } # return is local to lambda
result = callback.call(5) # => 10, no LocalJumpErrorWhy this works
return inside a lambda exits the lambda itself; return inside a Proc exits the enclosing method, which may be gone.
Code examples
Proc with return after enclosing method exitsruby
def make_proc
Proc.new { return 42 }
end
p = make_proc
p.call # LocalJumpError: unexpected returnLambda is saferuby
fn = ->(x) { return x * 2 }
fn.call(3) # => 6Rescue in iteratorsruby
def each_item(&block)
@items.each { |i| block.call(i) }
rescue LocalJumpError
# no block given — handle gracefully
endSame error in other languages
Sources
Official documentation ↗
Ruby Core Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev