liveBook · Manning

Binding

As explained in The Well-Grounded Rubyist, Fourth Edition

A variable is a Ruby identifier that refers to changeable stored information.

One object, two names

Try `str = "Hello"; abc = str; str.replace("Goodbye")`. Printing either variable now gives `Goodbye`. Assigning `str` to `abc` copied a reference, not the string itself; both names refer to the same object, and `replace` changed that object. section 2.5.1

A variable binding associates an identifier with an object. Assignment establishes that association; it does not put a separate copy of the object inside the variable. Ruby has local, instance, class, and global variables, recognizable by their names: `name`, `@name`, `@@name`, and `$name`. Each can be an assignment target. section 1.1.3 section 2.5.2

Reassignment is different from mutation

Now try `str = "Hello"; abc = str; str = "Goodbye"`. Printing `str` gives `Goodbye`, but printing `abc` still gives `Hello`. The second assignment gives `str` a reference to a different string; it does not change the original string or `abc`’s binding. section 2.5.2

References are the useful model for understanding why changes through one variable can appear through another. There are exceptions to how values are stored under the hood, notably integers, symbols, `true`, `false`, and `nil`. They do not change the distinction between assigning a variable and changing an object. section 2.5.1 section 2.5.2

Ruby also has a `Binding` class. Calling `binding` captures the local-variable bindings in effect at that point. Passed as the second argument to `eval`, that object lets an evaluated string use those locals: `eval("puts str", b)` can read `str` from the context captured in `b`, even when `str` is not in the calling method’s scope. Use `eval` cautiously. section 14.4.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Works through mutation and reassignment, then explains captured local bindings for `eval`; notes immediate-value exceptions without detailing their internals.
Examples
Contrasts string replacement with string reassignment and uses a captured top-level binding to evaluate `puts str` inside a method.
What it assumes
Assumes basic assignment and method-call syntax while introducing the reference model through small Ruby examples.
What you can do after
Diagnose/debug with it when two variables reflect one mutation but diverge after reassignment.
How it connects
Connects bindings to object references, variable scope, mutation, reassignment, and `eval`.

Also explained in

Compare how 11 books explain binding →

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.