为什么重新打开嵌套模块会根据所使用的语法给出不同的结果?例如,这可以正常工作:
Why does re-opening a nested module give different results depending on the syntax used? For example, this works fine:
module A module E end end module A module E def E.e end end end但是这个:
module A module E end end module A::E def E.e end end给出错误:
reopen.rb:6:in `<module:E>': uninitialized constant A::E::E (NameError) from reopen.rb:5:in `<main>'(在有人指出这一点之前,一种解决方法是在定义E.e时使用self而不是模块名称,但这并不是本文的重点.)
(Before someone points this out, a workaround is to use self instead of the module name when defining E.e, but that's not really the point of this post.)
推荐答案module关键字设置名称空间上下文,将检查该命名空间上下文中是否存在对Modules现有名称的引用.然后从内到外搜索这些名称空间,以解析对模块(和类)名称的引用.
The module keyword sets a namespace context that is checked for references to existing names of Modules. These namespaces are then searched inner-to-outer to resolve references to Module (and Class) names.
在第一个示例中,它看起来像,就像您可能需要在module E块中定义E.e一样,但实际上您不需要:
In your first example, it looks like you may need to define E.e inside module E block, but in fact you don't:
module A module E end end module A def E.e end end在两个示例中发生的都是Ruby查看当前名称空间,并尝试将<namespace>::E作为模块名称.因此,在两个示例中,它检查的第一件事实际上是A::E::E,它不存在.然后,它又回到了下一个上下文.这与示例有所不同:在第一个示例中,A::E有效,在第二个示例中,E无效.然后抛出的错误与它检查的名字有关.
What happens in both your examples is that Ruby looks at the current namespace, and tries <namespace>::E as a module name. So in both examples, the first thing it checks is in fact A::E::E which does not exist. Then it falls back to the next context. Which is where the examples differ: In the first example it is A::E which is valid, in the second example, it is just E which is not. The error that it then throws relates to the first name it checked.
更多推荐
重新打开Ruby中的嵌套模块异常
发布评论