Ruby 中的全局变量和常量在作用域上有什么区别?
What is the difference in scoping between a global variable and a constant in Ruby?
在 Ruby 编程语言中,既有全局变量的概念,以美元符号开头,例如 $foo
,也有以大写字母开头的常量,例如 Foo
。 Ruby 中这两种名称在范围上的确切区别是什么?在什么特定情况下,全局变量应该优先于常量,反之亦然?
全局变量是可以从任何地方访问的变量。它们的范围变成了整个 main
对象。这意味着它们可以在这个范围内的任何地方使用,即代码本身的任何地方。例如
module A
module B
class C
$glo = 'this is glo-bal variable'
end
end
end
module D
class E
CON = 'this is con-stant'
def call_glo
puts $glo
end
def call_con
puts CON
end
end
def self.call_con
puts CON
end
E.new.call_glo #=> "this is glo-bal variable"
end
D::E.new.call_glo #=> "this is glo-bal variable"
D::E.new.call_con #=> "this is con-stant"
D.call_con #=> Throws Error Unitialized Constant
虽然常量被限制在它们定义的范围内。它们只能在它们定义的范围内使用。
现在,正如您所说,常量以大写字母开头,因此所有 class 名称和模块名称本身就是常量。
现在在上面的示例中,您看到 call_glo
方法被调用了两次。一次来自 module D
的范围,一次来自 main
对象范围,你看到 class E
的实例化之间的区别了吗?
在module D
中调用时没有任何作用域运算符::
,而在模块外我们必须使用作用域运算符,这是作用域的限制。常量绑定到。
在 Ruby 编程语言中,既有全局变量的概念,以美元符号开头,例如 $foo
,也有以大写字母开头的常量,例如 Foo
。 Ruby 中这两种名称在范围上的确切区别是什么?在什么特定情况下,全局变量应该优先于常量,反之亦然?
全局变量是可以从任何地方访问的变量。它们的范围变成了整个 main
对象。这意味着它们可以在这个范围内的任何地方使用,即代码本身的任何地方。例如
module A
module B
class C
$glo = 'this is glo-bal variable'
end
end
end
module D
class E
CON = 'this is con-stant'
def call_glo
puts $glo
end
def call_con
puts CON
end
end
def self.call_con
puts CON
end
E.new.call_glo #=> "this is glo-bal variable"
end
D::E.new.call_glo #=> "this is glo-bal variable"
D::E.new.call_con #=> "this is con-stant"
D.call_con #=> Throws Error Unitialized Constant
虽然常量被限制在它们定义的范围内。它们只能在它们定义的范围内使用。
现在,正如您所说,常量以大写字母开头,因此所有 class 名称和模块名称本身就是常量。
现在在上面的示例中,您看到 call_glo
方法被调用了两次。一次来自 module D
的范围,一次来自 main
对象范围,你看到 class E
的实例化之间的区别了吗?
在module D
中调用时没有任何作用域运算符::
,而在模块外我们必须使用作用域运算符,这是作用域的限制。常量绑定到。