Variable References
A variable is simply a name for a value. Variables are created and values assigned to them by assignment expressions, which are covered later in this chapter. When the name of a variable appears in a program anywhere other than the lefthand side of an assignment, it is a variable reference expression and evaluates to the value of the variable:
one = 1.0 # This is an assignment expression one # This variable reference expression evaluates to 1.0
As explained in Chapter 2, there are four kinds
of variables in Ruby, and lexical rules govern their names. Variables
that begin with $ are global variables, visible throughout a Ruby program.
Variables that begin with @ and @@ are instance variables and class variables,
used in object-oriented programming and explained in Chapter 7. And variables whose names begin with an underscore
or a lowercase letter are local variables, defined only within the
current method or block. (See Blocks and Variable Scope for more
about the scope of local variables.)
Variables always have simple, unqualified names. If a . or :: appears in an expression, then that expression is either a
reference to a constant or a method invocation. For example, Math::PI is a reference to a constant, and the
expression item.price is an
invocation of the method named price
on the value held by the variable item.
The Ruby interpreter predefines a number of global variables when it starts up. See Chapter 10 for a list of these variables.
Uninitialized Variables ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access