我一直在阅读这本Ruby书,然后就是这个我不太了解的例子:
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中运行。 谢谢。
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"Would you please explain this to me (a detailed explanation) so I can fully understand how the scope works in Ruby. Thank you.
最满意答案
Ruby中的常量(以大写字母开头的标识符)可以根据定义/访问它们的词法范围进行访问。
在method1 , Mod作用域内的CONST优先于最外层的CONST 。 在method2 , Mod范围内的CONST在词法上是不可见的,因此访问最外面的CONST 。
至于方法定义本身,当名称用前面的模块常量限定(例如Mod或Mod::Inner )时,该方法被定义为“模块方法”而不是self.class的实例方法(默认情况下) )。
模块/方法层次结构中的名称由::或者在模块和模块方法之间的分隔符的情况下分隔,a . 。
更新 :请注意, Mod的常量对于method2不可见的原因是Mod没有单独“打开”。 该定义直接跳过Mod::Inner 。 如果代码更改为:
module Mod module Inner def (Mod::Inner).method2 ...然后,方法2可以访问Mod的常量,并优先于外部范围中的任何常量。
Constants in Ruby (identifiers beginning with a capital letter) are accessible based on the lexical scope in which they are defined/accessed.
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.
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 ..
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 ...Then Mod's constants would be accessible to method2 and take precedence over any in the outer scope.
更多推荐
发布评论