Global variables begin with $. They can be accessed anywhere in the program. The global variable has a special value nil before initialization.
ruby> $foo
nil
ruby> $foo = 5
5
ruby> $foo
5
Global variables should be used with caution. They are very dangerous because they can be written anywhere. Misuse of global variables can make it difficult to isolate bugs, as well as the design of programs that are not rigorously considered. When you find that you have to use a global variable, remember to give it a descriptive name that you don't accidentally use anywhere else ( It may not be a good idea to call $foo like the one above.
The advantage of global variables is that they can be tracked; You can do a procedure that is invoked when the value of a variable 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 an activator of a process, we also call it the active variable (active variable). For example, it can be used to keep the GUI display updated.
Here are some special variables that start with a $ with a single character. 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 Ruby's Reference manual):
$! Last error message
Where $@ errors are generated
$_ gets recently read string
$. The number of lines that the interpreter has recently read (line numbers)
$& the most recent string that matches a regular expression
$~ The most recent match as a child expression group
$n the most recently matched nth subexpression (same as $~[n])
$= whether or not to distinguish between uppercase and lowercase flags
$/Enter Record separator
$\ Output Record Separator
The file name of the $ ruby script
$* Command Line arguments
$$ Interpreter Process ID
$? Last child process exit status performed
The above $_ and $~ all have scope. Their names imply that they are global, but they are generally used in this way, and there are historical reasons for their naming.