Blocks, procs and iterators
Blocks are the heart of Ruby. A block is a chunk of code you pass to a method, between { } or do … end. Every each, map and select you've used takes one. In this lesson you'll learn how they work, how to write your own methods that take blocks, and the related objects: procs and lambdas.
Blocks
{ |x| … }is the usual style for one line;do |x| … endfor several lines.- The names between pipes (
|n|) are the block's parameters. - A block isn't a method argument in parentheses; it's attached to the call.
Blocks see the variables around them
Unlike methods, a block can use and change local variables from where it's written. That's called a closure:
it, _1 and &:method
Short blocks have shorthand forms:
Writing methods that take blocks: yield
Inside a method, yield runs the block that was passed in, and returns the block's value:
block_given? tells you whether a block was passed, so a method can do something sensible either way:
The resource pattern
Blocks are perfect for "set up, do something, always clean up". File.open with a block closes the file for you, even if an error happens. Here's the same pattern written by hand:
Procs and lambdas
A block can be saved in an object and called later. There are two kinds:
Lambda (->(x) { }) |
Proc (proc { |x| }) |
|
|---|---|---|
| Wrong number of arguments | Error, like a method | Ignored / filled with nil |
return inside |
Returns from the lambda | Returns from the surrounding method |
| Use for | Functions stored in variables | Rarely written directly |
Prefer lambdas. Their behaviour matches methods, so there are fewer surprises:
Capturing a block with &block
A method can receive its block as an object with &block, to store it or pass it on:
That's exactly how event handlers and callbacks work in Ruby libraries.
Iterators and Enumerators
Call each, map and friends without a block and you get an Enumerator: an object you can chain, step through by hand, or make lazy:
Enumerator.new with y << value is a generator: values are produced only as they're asked for.
Make your own class enumerable
Define each and include Enumerable, and your class gets map, select, sort, min, sum, first and 50 more for free:
Practice
- Write
def repeat(n)that yields the numbers 1 to n to its block, and use it to print a countdown. - Write
def retry_times(n)that calls its block until it returns a truthy value or n attempts have run. - Store three lambdas (
double,square,negate) in a hash and apply them by name to the number 7. - Make a
Countdownclass that includesEnumerableand counts down from a given number.
1.What does yield do inside a method?
2.What does [1, 2].map(&:to_s) mean?
3.What's a key difference between a lambda and a proc?
4.What do you need to make your class support map, select and sort?