liveBook · Manning

Block-local variable

As explained in The Well-Grounded Rubyist, Fourth Edition

A block-local variable is a variable declared after the semicolon in a block parameter list and kept distinct from same-named variables outside the block.

A block-local variable is declared after a semicolon in a block parameter list. Ruby gives it a new identity inside the block, even when an outer variable has the same name. section 6.3.8

Preserving an outer value

Given an outer `fahrenheit`, write `celsius.each do |c;fahrenheit|`. Assignments to `fahrenheit` now serve as temporary block values, leaving the original outer value unchanged after iteration. section 6.3.8

Distinguish the three block-variable forms:

  • Existing local variables can be read and reassigned inside the block, so reassignment may remain visible afterward. section 6.3.8
  • Block parameters are bound to values supplied when the block runs and remain local to the block. section 6.3.8
  • True block-locals follow a semicolon, receive no argument, and protect temporary names from outer-scope collisions. section 6.3.8

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains semicolon syntax, binding behavior, and contrast with ordinary locals and block parameters.
Examples
Uses a Temperature conversion loop to show outer-value preservation during repeated block assignments.
What it assumes
Assumes familiarity with Ruby blocks, block parameters, local variables, and assignment.
What you can do after
Apply it in Ruby block syntax to isolate temporary assignments and preserve surrounding local-variable values.
How it connects
Connects block-local variables with block parameters, local variables, variable scope, and variable name collisions.

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.