When Ruby sees a name such as ``a'' in an expression, it needs to
determine if it is a local variable reference or a call to a method
with no parameters.
To decide which is the case, Ruby uses a
heuristic. As Ruby reads a source file, it keeps track of symbols
that have been assigned to. It assumes that these symbols are variables. When it
subsequently comes across a symbol that might be either a variable or
a method call, it checks to see if it has seen a prior assignment to
that symbol. If so, it treats the symbol as a variable; otherwise it
treats it as a method call. As a somewhat pathological case of this,
consider the following code fragment, submitted by Clemens Hintze.
def a
print "Function 'a' called\n"
99
end
for i in 1..2
if i == 2
print "a=", a, "\n"
else
a = 1
print "a=", a, "\n"
end
end
|
produces:
a=1
Function 'a' called
a=99
|
During the parse, Ruby sees the use of ``a'' in the first print
statement and, as it hasn't yet seen any assignment to ``a,'' assumes
that it is a method call. By the time it gets to the second print
statement, though, it
has seen an assignment, and so treats
``a'' as a variable.
Note that the assignment does not have to be executed---Ruby just has
to have seen it. This program does not raise an error.