Notes for variable reference IN Ruby: Ruby variable reference
In the expression, when Ruby sees a name like a, it needs to determine whether a is a local variable reference or a call to method a without parameters. Ruby uses a heuristic method to determine this situation. When Ruby parses the source code file, it records all the symbols that have been assigned values. It considers these symbols as variables. In the future, when a symbol can be both a variable and a method call, Ruby checks whether the symbol has been assigned a value. If yes, use this symbol as a variable; otherwise, use it as a method call. The following is an example of human design that describes this situation.
Def a print "Funciton 'A' called \ n" 99end for I in 1 .. 2 if I = 2 print "a =", a, "\ n" else a = 1 print "a =", a, "\ n" endend
Output result:
A = 1 Function 'A' calleda = 99
When parsing, Ruby sees that the first print statement uses a, and has not encountered any value assignment statement on a, so it is called as a method. However, when parsing the second print statement, Ruby treats it as a variable because it encounters a value assignment statement for.
Note that the value assignment statement is not always executed-as long as Ruby sees it. The following program will not cause errors
A = 1 if false;