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.
1
A Block = Attached Code
Write it between braces { } or do...end and glue it onto any method call.
2
yield Runs It
Inside your own method, yield hands control over to the attached block.
3
Procs Are Objects
Proc.new wraps a block in an object — store it, pass it, call it later with .call.
4
Lambdas Act Like Methods
lambda makes a stricter proc: it counts its arguments and returns like a method.
Code you can attach and carry
A Block = Attached Code1Write it between braces { } or do...end and glue it onto any method call.
yield Runs It2Inside your own method, yield hands control over to the attached block.
Procs Are Objects3Proc.new wraps a block in an object — store it, pass it, call it later with .call.
Lambdas Act Like Methods4lambda makes a stricter proc: it counts its arguments and returns like a method.
4 building blocks make up Code you can attach and carry
Watch it run
Blocks in action
Two little programs: one shows a block running per element, one shows blocks stored as objects.
each_demo.rb
1[1,2,3].eachdo|n|
2puts n *2
3end
4puts"done"
block
each starts: it yields the first element, and the block parameter |n| catches 1.
Memory
n= 1
Console
output appears as the program runs…
Step 1/8
In 3D
Watch each walk the array
each visits the cells one by one and yields every value to your block. Play the script, then drag to orbit.
Drag to orbit the scene. Press Play to watch memory in action.
Practice
Match the callable vocabulary
Click a term, then click its description to lock the pair.
5 conceptsTap a card to expand
?do ... enddrops into place
?yielddrops into place
?Proc.new { }drops into place
?lambda { }drops into place
?&:upcasedrops into place
Challenge
Predict the output
One loop collects a total, one lambda gets reused by map.
blocks.rb
1total =0
2[2,4,6].eachdo|n|
3 total = total + n
4end
5puts total
6
7double =lambda{|x| x *2}
8puts double.call(3)
9puts[1,2].map(&double).length
Your predicted output — one line per console line
Hint: each runs the block once per element, in order, so total gathers 2 + 4 + 6. map(&double) calls the lambda on every element and collects the results in a new array of two items.
Recap
Key takeaways
Key takeaways5 takeaways
01
Attach a block with { } or do...end; the method runs it with yield.
02
each yields one element at a time; |n| names the parameter that catches it.
03
Proc.new and lambda turn blocks into objects with a call method.
04
Lambdas behave like methods: strict arity, return exits the lambda.
05
&:method is the shortcut for calling one method on every element.