concept local scope in category ruby

appears as: local scope, local scope, local scopes, local scopes
The Well-Grounded Rubyist, Third Edition

This is an excerpt from Manning's book The Well-Grounded Rubyist, Third Edition.

Scope is an important topic in its own right, and we’ll get deeply into it in chapter 5. You can start getting familiar with some key aspects of it now, though, as you examine how local variables come and go. The classic case of local scope is a method definition. Watch what happens with x in this example:

Local scope is a basic layer of the fabric of every Ruby program. At any given moment, your program is in a particular local scope. The main thing that changes from one local scope to another is your supply of local variables. When you leave a local scope—by returning from a method call, or by doing something that triggers a new local scope—you get a new supply. Even if you’ve assigned to a local variable x in one scope, you can assign to a new x in a new scope, and the two x’s won’t interfere with each other.

You can tell by looking at a Ruby program where the local scopes begin and end, based on a few rules:

Every time you cross into a class-, module-, or method-definition block—every time you step over a class, module, or def keyword—you start a new local scope. (Figure 5.2 illustrates the creation of a number of local scopes.) Local variables that lie very close to each other physically may in fact have nothing whatsoever to do with each other, as this example shows:

Figure 5.2. Schematic view of local scopes at the top level, the class-definition level, and the method-definition level

5.2.3. The interaction between local scope and self

When you start a definition block (method, class, module), you start a new local scope, and you also create a block of code with a particular self. But local scope and self don’t operate entirely in parallel, not only because they’re not the same thing, but also because they’re not the same kind of thing.