Blocks, Procs and Lambdas

Lesson 11 of 20

Attach chunks of code to method calls, store them in variables as Procs and lambdas, and hand them around like objects.

The big picture

Code you can attach and carry

Blocks are chunks of code glued to method calls — the secret behind each, times and every elegant Ruby loop. Procs and lambdas turn them into objects you can keep.

A Block = Attached Code

Write it between braces { } or do...end and glue it onto any method call.

yield Runs It

Inside your own method, yield hands control over to the attached block.

Procs Are Objects

Proc.new wraps a block in an object — store it, pass it, call it later with .call.

Lambdas Act Like Methods

lambda makes a stricter proc: it counts its arguments and returns like a method.