重新打开Ruby中的嵌套模块异常

编程入门 行业动态 更新时间:2024-10-27 16:23:55
本文介绍了重新打开Ruby中的嵌套模块异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

为什么重新打开嵌套模块会根据所使用的语法给出不同的结果?例如,这可以正常工作:

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中的嵌套模块异常

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

发布评论

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

>www.elefans.com

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