Limited Offer
60% OFF on all plans!

Blocks, Procs & Lambdas in Ruby

Master Ruby's closures — blocks, Procs, and Lambdas — and understand how they differ and when to use each.

Blocks

A block is an anonymous chunk of code that can be passed to a method. You write it with do...end or curly braces { }. Blocks are not objects — they are syntactic constructs.

1. Block with do...end

Pass a block to a method.

2. Block with { }

One-liner block syntax.

3. yield — Calling the Block Inside a Method

yield invokes the passed block.

4. yield with Arguments

Pass values from method to block.

5. block_given? — Optional Blocks

Check if a block was provided.

Procs

A Proc is a block that has been saved as an object. You can store it, pass it around, and call it later. Procs are closures — they remember the scope where they were created.

1. Creating and Calling a Proc

Create a reusable block object.

2. Proc as Closure

Proc captures outer variables.

3. Converting Proc to Block with &

Pass a Proc where a block is expected.

4. Symbol#to_proc Shorthand

Use :method_name as a block shorthand.

Lambdas

A Lambda is like a Proc but with stricter argument checking and different return behavior. Create with lambda { } or the stabby arrow -> { }.

1. Creating and Calling a Lambda

Lambda with lambda keyword.

2. Stabby Lambda (->)

Concise lambda syntax.

3. Lambda Strict Argument Checking

Lambda enforces argument count.

4. Lambda vs Proc: return Behavior

return inside lambda vs Proc behaves differently.

Closures

Blocks, Procs, and Lambdas are all closures in Ruby. They capture variables from the surrounding scope and remember them even after that scope has ended.

1. Closure Variable Capture

Closures remember outer variables.

2. Closure as Factory Function

Return a closure that remembers state.

Proc vs Lambda — Key Differences

Procs and Lambdas look similar but have two critical differences: argument checking and return behavior.

1. Side-by-Side Comparison

Argument checking and return.