全局变量

    全局变量

    A global variable has a name beginning with $.

    全局变量的名字以开头。

    It can be referred to from anywhere in a program. Before initialization, a global variable has the special value nil.

    你可以在程序的任何地方引用全局变量。在对其进行初始化之前,一个全局变量的值是特殊的nil值。

    Global variables should be used sparingly.

    应当谨慎使用全局变量

    They are dangerous because they can be written to from anywhere.

    Overuse of globals can make isolating bugs difficult; it also tends to indicate that the design of a program has not been carefully thought out.

    过度使用全局变量会使隔离Bug变得很困难;它也倾向于表明一个程序的设计并没有经过仔细的考虑。

    Whenever you do find it necessary to use a global variable, be sure to give it a descriptive name that is unlikely to be inadvertently used for something else later (calling it something like $foo as above is probably a bad idea).

    无论何时,当你发现确实有必要使用全局变量时,一定要给它一个描述性的名称,这个名称不太可能在以后因为其他事情而无意中使用它(将其命名为$foo很可能是一个坏主意)。

    One nice feature of a global variable is that it can be traced; you can specify a procedure which is invoked whenever the value of the variable is changed.

    全局变量的一个很好的特性是它可以被跟踪;你可以指定一个过程,该过程在变量的值被更改时被调用。

    1. ruby> trace_var :$x, proc{puts "$x is now #{$x}"}
    2. ruby> $x = 5
    3. 5

    When a global variable has been rigged to work as a trigger to invoke a procedure whenever changed, we sometimes call it an active variable.

    当一个全局变量被操纵,作为触发器来调用一个过程时,我们有时会把它称为一个活动变量

    例如,对于保持GUI展示最新内容,全局变量可能有用。

    There is a collection of special variables whose names consist of a dollar sign ($) followed by a single character.

    有一组特殊的变量,它们的名字由一个美元符号()组成,后面跟着一个字符。

    For example, $$ contains the process id of the ruby interpreter, and is read-only. Here are the major system variables:

    例如,$$包含Ruby解释器的进程id,并且是只读的。以下是主要的系统变量:

    In the above, $_ and $~ have local scope.

    上面的$_$~都有局部作用域。

    Their names suggest they should be global, but they are much more useful this way, and there are historical reasons for using these names.


    下一章 实例变量