An interactive Ruby lesson
Blocks, then closures
Tell Ruby what to do. Then find out what that code remembers.
New to Ruby? Start at the beginning. If you already use blocks, jump to closures.
The first Run downloads Ruby into your browser. It may take a moment. Each run starts fresh; edits stay in your browser. JavaScript and a network connection are needed to run examples. The code and answers remain readable without them.
Part 1: blocks
A block is a piece of code passed to a method. Here, each visits every name and runs the block for each one.
1. Say hello
Predict the output. Then run the code. Try changing a name or the message.
Show expected output
Hello, Ana! Hello, Ben! Hello, Cora!
do ... end marks the block. |name| names the current item. each handles iteration; the block supplies the action.
2. Collect results with map
Predict: does this print three separate lines or one array?
Show answer
One array: ["Hello, Ana!", "Hello, Ben!", "Hello, Cora!"]. map collects each block result in a new array.
3. Call a block yourself
A method can use yield to call the block it receives.
Show expected output
Welcome to the meetup! Glad you're here, Ana.
The method decides when to call the block. The caller decides what the block does. Try changing the block's message.
Part 2: closures
A closure retains access to variables from its surrounding scope. A lambda is a callable object that can carry that access beyond the method that created it. A block can also be captured as a Proc; here we use lambdas.
4. Two counters
Predict the four numbers. Do the counters share a count?
Show answer
1 2 1 3
Each call to make_counter creates a separate count. Each lambda retains access to its own variable after the method returns.
5. Two closures, one variable
Predict what read prints before and after two increments.
Show answer
0 2
Both lambdas retain access to the same variable. One changes it; the other reads it. Try making another pair. Does it share the first pair's count?
6. Carry configuration
A closure can carry a setting with behavior. Change the prefixes and names.
Show expected output
Good evening, Ana! Hey, Ana!
Keep learning
- Make the greeting block print a different message for each name.
- Add a
decrementlambda to the shared counter. What doesreadshow? - Read the Ruby documentation on blocks and Proc and lambda documentation.
The runner uses ruby.wasm. Browser Ruby has environment limits; these examples do not require Rails or a Ruby server.