ruby全局变量
Global Variables are variables that may be accessed from anywhere in the program regardless of scope. They're denoted by beginning with a $ (dollar sign) character. However, the use of global variables is often considered "un-Ruby," and you will rarely see them.
全局变量是可以从程序中的任何位置访问的变量 ,无论其范围如何。 它们以$(美元符号)字符开头。 但是,全局变量的使用通常被认为是“ un-Ruby”,并且您很少会看到它们。
定义全局变量 ( Defining Global Variables )
Global variables are defined and used like any other variable. To define them, simply assign a value to them and begin using them. But, as their name suggests, assigning to global variables from any point in the program has global implications. The following program demonstrates this. The method will modify a global variable, and that will affect how the second method runs.
全局变量的定义和使用与其他任何变量一样。 要定义它们,只需为它们分配一个值并开始使用它们。 但是,顾名思义,从程序的任何位置分配全局变量都具有全局含义。 下面的程序演示了这一点。 该方法将修改全局变量,这将影响第二种方法的运行方式。
$speed = 10
def accelerate
$speed = 100
end
def pass_speed_trap
if $speed > 65
# Give the program a speeding ticket
end
end
accelerate
pass_speed_trap