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 expected output
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 is code that keeps access to local variables from where it was created. Think of it as code carrying a connection to those variables. It can read or change them later, even after the method that created it has returned.
In the next examples, each -> { ... } creates a lambda, a callable object. Call it with .call. The lambda and the variables it can access form a closure.
4. Two counters
Predict the four numbers. Do the counters share a count?
Show expected output
1 2 1 3
Each call to make_counter creates its own count and returns a lambda. After the method returns, each call to that lambda reads and increases its own count. The second counter starts at zero because it has a separate variable.
5. Two closures, one variable
Predict what read prints before and after two increments.
Show expected output
0 2
The method returns both lambdas. After it returns, increment.call reads and increases their shared count; read.call reads its current value. 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!
Each returned lambda keeps access to the prefix passed to its own call of greeting_formatter. Later, it reads that prefix and combines it with the name.
Procs and lambdas
Both a proc created with proc and a lambda are Proc objects. Both can act as closures. They differ in how they handle arguments and return.
For these simple parameters, a proc fills a missing argument with nil and ignores extra arguments. A lambda checks the number of arguments and raises ArgumentError when it is wrong.
loose = proc { |a, b| [a, b] }
strict = ->(a, b) { [a, b] }
p loose.call(1) # [1, nil]
p loose.call(1, 2, 3) # [1, 2]
begin
strict.call(1)
rescue ArgumentError
puts "Wrong number of arguments"
end
Show expected output
[1, nil] [1, 2] Wrong number of arguments
Inside a lambda, return returns from the lambda. Inside a non-lambda proc, return attempts to return from the method where the proc was defined. If that method has already returned, calling the proc raises LocalJumpError.
def proc_example
action = proc { return "Left the method" }
action.call
"This line is skipped"
end
def lambda_example
action = -> { return "Left the lambda" }
puts action.call
"The method continues"
end
puts proc_example
puts lambda_example
Show expected output
Left the method Left the lambda The method continues
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.