liveBook · Manning

Block parameter

As explained in The Well-Grounded Rubyist, Fourth Edition

A block parameter is a formal input listed between pipes in a Ruby block and bound to a value when the block is invoked.

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

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains pipe syntax, method-style parameter patterns, scope contrasts, and yielded values, while deferring closures to later treatment.
Examples
Uses argument unpacking, repeated iteration, variable-scope demonstrations, temperature conversion, and a threaded date server.
What it assumes
Assumes familiarity with method arguments and method calls while demonstrating block syntax and scope behavior.
What you can do after
Apply it via Ruby blocks by declaring pipe-delimited inputs and predicting their bindings and scope behavior.
How it connects
Connects block parameters with method arguments, variable scope, method calls, closures, Proc objects, iteration, and threads.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.