模块如何解决常数的范围?(How Do Modules Resolve A Constant's Scope?)

编程入门 行业动态 更新时间:2024-10-19 00:22:56
模块如何解决常数的范围?(How Do Modules Resolve A Constant's Scope?)

我一直在阅读这本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.

更多推荐

本文发布于:2023-08-06 22:25:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1456731.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:常数   如何解决   模块   Modules   Constant

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!