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.