Junior Track Roadmap

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
Free preview · Lesson 1 3 min read

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 lessons
Type to start searching...