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
  1. 1Calling a Proc (stored from a block) after the enclosing method has returned
  2. 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 LocalJumpError

Why 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 return
Lambda is saferuby
fn = ->(x) { return x * 2 }
fn.call(3)   # => 6
Rescue in iteratorsruby
def each_item(&block)
  @items.each { |i| block.call(i) }
rescue LocalJumpError
  # no block given — handle gracefully
end
Sources
Official documentation ↗

Ruby Core Documentation

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Ruby errors