From the "Programming Ruby Book": Show archive.org snapshot
Assignment to a variable works as you would expect: the variable is simply set to the specified value. The only wrinkle has to do with variable declaration and an ambiguity between local variable names and method names. Ruby has no syntax to explicitly declare a variable: variables simply come into existence when they are assigned. Also, local variable names and method names look the same—there is no prefix like $ to distinguish them. Thus, a simple expression such as x could refer to a local variable named x or a method of self named x. To resolve this ambiguity, Ruby treats an identifier as a local variable if it has seen any previous assignment to the variable. It does this even if that assignment was never executed. The following code demonstrates:
class Ambiguous
def x; 1; end # A method named "x". Always returns 1
def test
puts x # No variable has been seen; refers to method above: prints 1
# The line below is never evaluated, because of the "if false" clause. But
# the parser sees it and treats x as a variable for the rest of the method.
x = 0 if false
puts x # x is a variable, but has never been assigned to: prints nil
x = 2 # This assignment does get evaluated
puts x # So now this line prints 2
end
end
That also means that you cannot assign the return value of x
to a local variable named x
:
class Ambiguous
def x; 1; end # A method named "x". Always returns 1
def test
puts x # No variable has been seen; refers to method above: prints 1
# The line below *is* evaluated. And one could assume since the right hand side of
# the expressions is executed first, that the return value of x would be assigned to
# the local variable x, however since at *parse time* ruby already pegged x as local variable
# it never calls the method x and the value of x remains 0
x = x
puts x # x is a variable, but has never been assigned to: prints nil
end
end