Some points to note when variable references in Ruby _ruby topics

Source: Internet
Author: User

In an expression, when Ruby sees a name like a, it needs to decide whether a is a local variable reference or a call to method a with no parameters. Ruby uses a heuristic approach to judge this situation. When ruby resolves the source code file, it records all the symbols that have been assigned. It considers these symbols to be variables. In the future, when you encounter a symbol that can be both a variable and a method call, Ruby checks to see if the symbol has been assigned a value. If so, treat the symbol as a variable, or as a method call. Here is an example of a contrived design that describes this situation.

def a
  print "Funciton ' a ' called\n" "The" I
 
in 1..2
  if I ==2
   print "a=", A, "\ n"
  else
   a=1
   print "a=", A, "\ n" End

Output results:

A=1
Function ' a ' called
a=99

When parsing, Ruby sees the first print statement using a, and as a method call because it has not encountered any assignment statements to a. But when parsing to the second print statement, Ruby encounters an assignment statement to a, so it is treated as a variable

Note that the assignment statement is not necessarily executed-as long as Ruby sees it. The following program does not cause an error

A=1 if False;a

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.