当使用 :: 指定模块时,为什么 Ruby 不能在更高范围内找到类? [英] Why doesn't Ruby find classes in a higher scope when module is specified using ::?

查看:51
本文介绍了当使用 :: 指定模块时,为什么 Ruby 不能在更高范围内找到类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是被这个问题困住了一段时间.以这个基地:

I just got stuck on this for a while. Take this base:

module Top
  class Test
  end

  module Foo
  end
end

稍后,我可以在 Foo 中定义扩展 Test 的类:

Later, I can define classes inside Foo that extends Test by doing this:

module Top
  module Foo
    class SomeTest < Test
    end
  end
end

但是,如果我尝试通过使用 :: 指定模块来最小化缩进:

However, if I try to minimize indentation by using :: to specify the module:

module Top::Foo
  class Failure < Test
  end
end

这失败了:

NameError: 未初始化的常量 Top::Foo::Test

NameError: uninitialized constant Top::Foo::Test

这是一个错误,还是只是 Ruby 解析变量名称方式的逻辑结果?

Is this a bug, or is it just a logical consequence of the way Ruby resolves variable names?

推荐答案

这是一个错误,还是只是一个合乎逻辑的结果

Is this a bug, or is it just a logical consequence

这是一个怪癖".有些人认为这是一个错误.

It's a "quirk". Some consider it a bug.

用于查找未解析常量的父作用域由模块嵌套决定.碰巧的是,当您使用 module Top::Foo 时,它只创建了一层而不是两层嵌套.观察:

Parent scopes used for looking up unresolved constants are determined by module nesting. It just so happens that when you use module Top::Foo, it creates just one level of nesting instead of two. Observe:

module Top
  module Foo
    class SomeTest
      Module.nesting # => [Top::Foo::SomeTest, Top::Foo, Top]
    end
  end
end

module Top::Foo
  class SomeTest
    Module.nesting # => [Top::Foo::SomeTest, Top::Foo]
  end
end

这篇关于当使用 :: 指定模块时,为什么 Ruby 不能在更高范围内找到类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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