Parse ruby global variables

Source: Internet
Author: User

Global variables start with $. They can be accessed anywhere in the program. Before initialization, the global variables have a special value nil.

Ruby> $ foo
Nil
Ruby> $ foo = 5
5
Ruby> $ foo
5

Use global variables with caution. they are quite dangerous because they can be written anywhere. misuse of global variables can make it difficult to isolate bugs. It is also considered that the program design is not strictly considered. when you find that you must use a global variable, remember to give it a descriptive name that will not be used accidentally elsewhere (calling $ foo as above may not be a good idea ).

The advantage of global variables is that they can be tracked. You can call a process when the variable value changes.

Ruby> trace_var: $ x, proc {print "$ x is now", $ x, "\ n "}
Nil
Ruby> $ x = 5
$ X is now 5
5

When a global variable (when changed) acts as the initiator of a process, we also call it an active variable. For example, it can be used to keep the GUI display updated.

Special variables starting with $ and with a single character are listed here. for example, $ contains the process id of the Ruby interpreter, which is read-only. here are the main system variables and their meanings (details can be found in the Ruby reference manual ):

$! Last error message
$ @ Error location
$ _ Gets recently read string
$. Number of lines recently read by the interpreter (line number)
$ & The latest string matching the Regular Expression
$ ~ Last match as a child expression group
$ N the nth subexpression (and $ ~ [N] Same)
$ = Case-insensitive flag
$/Input record Separator
$ \ Output record Separator
$0 Ruby script file name
$ * Command line parameters
$ Interpreter process ID
$? The last sub-process exited

The above $ _ and $ ~ Their names indicate global, but they are generally used in this way. There are historical reasons for their names.

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.