重新打开Ruby中的嵌套模块异常 [英] Re-opened nested module anomaly in Ruby

查看:59
本文介绍了重新打开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中的嵌套模块异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆