Ruby closures: procs & lambdas
This course explains what a closure is in Ruby: a Proc or lambda that captures the local variables in scope when it is created and keeps live access to them. It builds a counter factory whose state is reachable only through the returned lambda. It compares return inside a lambda, which exits only the lambda, with return inside a Proc, which exits its creating method. It covers the LocalJumpError raised when a Proc outlives its method, and storing lambdas in a Hash to call them by key.
What you'll learn
- ✓What a closure captures and why it keeps a live link to variables
- ✓Building a method that returns a closure with private, ongoing state
- ✓How return behaves inside a lambda compared with inside a Proc
- ✓Why a Proc with return raises LocalJumpError after its method finishes
- ✓Storing lambdas in a Hash and calling them by a key chosen at runtime
What a closure captures
The Ruby blocks (do..end) course's lesson "Proc and lambda: a brief look" already covered real ground. &block turns a passed block into a Proc object, and Proc.new and proc build one directly. .call, .() and [] are three ways to run one. lambda and the ->() { } stabby literal build a stricter…
Read the full lesson free →Curriculum
7 lessonsWhat a closure captures
Defines a closure as a Proc or lambda keeping live access to local variables captured at creation.
A counter factory with its own state
Builds make_counter, whose lambda reassigns its own private count, with each call producing independent state.
return inside a lambda: exits only the lambda
Shows that return inside a lambda exits only the lambda, while the enclosing method keeps running.
return inside a Proc: exits the enclosing method
Shows that return inside a Proc exits the method where the Proc was created, skipping later lines.
LocalJumpError: when a Proc outlives its method
Explains why calling a Proc with return after its creating method finished raises LocalJumpError: unexpected return.
Storing procs in a hash, called dynamically
Stores lambdas as Hash values and picks one by a runtime key, avoiding a growing if/elsif chain.
Putting it together: closures, procs, and lambdas
Reviews all six lessons and combines them in make_account_logger, two lambdas sharing private captured state.