模块如何解析常量的作用域? [英] How Do Modules Resolve A Constant's Scope?
问题描述
我一直在阅读这本Ruby书,然后有一个我不太了解的示例:
I've been reading this Ruby book, then there's this example that I haven't well understood :
CONST = "outer"
module Mod
CONST = 1
def Mod.method1
# module method
CONST + 1
end
end
module Mod::Inner
def (Mod::Inner).method2
CONST + " scope"
end
end
Mod::CONST # => 1
Mod.method1 # => 2
Mod::Inner::method2 # => "outer scope"
请您向我解释一下(详细解释),以便我可以完全理解该作用域在Ruby中的工作方式. 谢谢.
Would you please explain this to me (a detailed explanation) so I can fully understand how the scope works in Ruby. Thank you.
推荐答案
Ruby的常量(以大写字母开头的标识符)可根据定义/访问它们的 lexical 范围进行访问.
Constants in Ruby (identifiers beginning with a capital letter) are accessible based on the lexical scope in which they are defined/accessed.
在method1
中,Mod
范围内的CONST
优先于最外面的CONST
.在method2
中,Mod
范围内的CONST
在词法上不可见,因此可以访问最外面的CONST
.
In method1
, the CONST
within the Mod
scope takes precedence over the outermost CONST
. In method2
, the CONST
within the Mod
scope is not visible lexically, so the outermost CONST
is accessed.
对于方法定义本身,当名称使用前面的模块常量(例如,Mod
或Mod::Inner
)限定时,该方法被定义为模块方法",而不是
As for the method definitions themselves, when the name is qualified with a preceding module constant (e.g. Mod
or Mod::Inner
), the method is defined as a "module method" rather than as an instance method of self.class
(the default).
模块/方法层次结构中的名称用::
分隔,或者在模块和模块方法之间用分隔符的情况下,用.
分隔.
Names in the module/method hierarchy are separated by ::
or, alternatively in the case of the separator between the module and the module method, a .
.
更新:请注意,method2
常量对method2
不可见的原因是Mod
没有单独打开".该定义直接跳到Mod::Inner
.如果代码更改为:
Update: Note that the reason why Mod
's constants are not visible to method2
is that Mod
was not separately "opened". The definition skipped directly to Mod::Inner
. If the code were changed to:
module Mod
module Inner
def (Mod::Inner).method2
...
然后Mod
的常量将可供method2
访问,并优先于外部范围中的任何常量.
Then Mod
's constants would be accessible to method2
and take precedence over any in the outer scope.
这篇关于模块如何解析常量的作用域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!