Prev - DUP - Next - TOC

Global variables


A global variable has `$'-prepended name and it can be referred from anywhere in the program. Before initialization, the global variable has a special value `nil'.

 ruby> $foo
 nil
 ruby> $foo = 5
 5
 ruby> $foo
 5

One can refer and change the global variable, so, it means that careless uses are dangerous because the effects are spread program-wide. You should not use it often. If you use it, you should name it redundantly to not be coincide to another one (it is because of the above naming `$foo' is bad example).

One can trace the global variable. So, you can specify the procedure which is invoked when the value of the global value is changed.

 ruby> trace_var :$x, proc{print "$x = ", $x, "\n"}
 nil
 ruby> $x = 5
 $x = 5
 5

As the above example, for a variable working as a trigger which invoke a procedure when the variable is chaged, we often call such a variable an `active variable'. For instance, it is useful for displaying the current value whenever it is changed in the case of a GUI.

In global variables, most names with one letter following `$' are known as system variables and have special meanings. For example, `$$' is referred as the process id of the ruby interpreter and it is read-only. The following list are major system variables:

    $!              error message
    $@              position of an error occurrence
    $_              latest read string by `gets'
    $.              latest read number of line by interpreter
    $&              latest matched string by the regexep.
    $1, $2...       latest matched string by nth parentheses of regexp. 
    $~              data for latest matche for regexp
    $=              whether or not case-sensitive in string matching
    $/              input record separator
    $\              output record separator
    $0              the name of the ruby scpript file
    $*              command line arguments for the ruby scpript
    $$              PID for ruby interpreter
    $?              status of the latest executed child process

In the above, `$_' and `$~' are treated as local scope. So, it doesn't influence outside the method even if the value is changed. These should be remarked as exceptions.


Prev - DUP - Next - TOC