Ruby blocks (do..end)
This course explains how Ruby methods receive and run blocks. It starts with yield, which runs the block passed to a method, and shows how yield hands values in and returns the block's result. It covers block_given? for optional blocks and the LocalJumpError raised when no block is given. It shows how &block captures a block as a Proc and forwards it to another method. The lessons rebuild each, map and select, take a brief look at Proc and lambda, and end with a small challenge.
What you'll learn
- ✓How yield runs the block a method received
- ✓Passing values to a block with yield and using its return value
- ✓Making a block optional with block_given?
- ✓Capturing a block with &block and forwarding it to another method
- ✓Rebuilding each, map and select with a loop, yield and an accumulator
- ✓Recognizing Proc and lambda and how they differ on argument count
yield: running the block a method received
The last three courses used each, map and select constantly, methods that receive a block and run it. None of them showed how a method does that. The answer is yield.
Read the full lesson free →Curriculum
7 lessonsyield: running the block a method received
Shows how yield runs a method's block at that point, and how each, map and times rely on it.
yield with arguments
Passes values into the block with yield, rebuilds the core of each, and uses the block's return value.
block_given? and optional blocks
Explains the LocalJumpError from yield without a block and uses block_given? to make blocks optional.
Capturing a block with &
Captures a block as a named Proc with &block, runs it with call, and forwards it.
Reimplementing map and select
Writes my_map and my_select from each, yield and an accumulator, showing their shared structure.
Proc and lambda: a brief look
Builds Proc objects and lambdas directly and shows that a lambda enforces its argument count.
Putting it together: a small challenge
Combines block_given?, yield and an accumulator in a build_list method, then asks you to write it.