Notes for variable reference IN Ruby: Ruby variable reference

Source: Internet
Author: User

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;

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.