A block parameter is a formal input written between pipes. Ruby binds it to a value when the block is invoked, much like a method parameter. section 6.3.8
Matching method-style argument patterns
A block can receive required parameters, defaults, a splat, and trailing parameters: block_args_unleashed do |a, b = 1, *c, d, e| ... end. Yielding 1, 2, 3, 4, and 5 binds a=1, b=2, c=[3], d=4, and e=5. section 6.3.8
Block parameters interact with surrounding local variables in a specific way:
- A non-parameter variable inside a block can refer to a variable already in the surrounding scope. section 6.3.8
- Assigning to that existing variable inside the block changes the value visible after the block finishes. section 6.3.8
- A parameter with the same name is separate from the surrounding variable; reassigning it does not change the outer value. section 6.3.8
A block is part of a method call rather than another method argument. The method may yield values to its block parameters, while the block remains optional and independent from the argument list. section 6.3.3
def block_local_parameter
x = 100 #1
[1,2,3].each do |x| #2
puts "Parameter x is #{x}"
x = x + 10 #3
puts "Reassigned to x in block; it's now #{x}"
end
puts "Outer x is still #{x}"
end
Inspect the difference between a block parameter named x and an outer local variable also named x. section 6.3.8
Per-thread state
Thread.new(conn) do |c| ... end yields conn to the block parameter c. Each thread therefore keeps its own connection reference instead of sharing the outer conn variable. section 14.5.2
