在两个不同的Ruby文件中使用相同名称的模块

在两个不同的Ruby文件中使用相同名称的模块,ruby,Ruby,我的“文件1” 还有我的目录 C:\Ruby200\lib\ruby\gems\2.0.0\gems\page-object-0.9.2\lib\page-object 由于安装了页面对象gem,因此位于我的硬盘上 在“文件1”的内容中,在其他代码行中,我看到以下行: require 'page-object/page_populator' 在同一文件的下方,我看到: module PageObject include PagePopulator 查看“文件2” 这些行位于该文件的顶部

我的“文件1”

还有我的目录

C:\Ruby200\lib\ruby\gems\2.0.0\gems\page-object-0.9.2\lib\page-object
由于安装了页面对象gem,因此位于我的硬盘上

在“文件1”的内容中,在其他代码行中,我看到以下行:

require 'page-object/page_populator'
在同一文件的下方,我看到:

module PageObject
  include PagePopulator
查看“文件2”

这些行位于该文件的顶部:

module PageObject
  module PagePopulator
根据我读到的Ruby教程,在使用
require
将“文件2”转换为“文件1”之后,“文件2”中的模块需要使用
include
转换为“文件1”

我希望“文件1”有

而不是

include PagePopulator
include Bar
但是,由于它不是这样设置的,而且page object是一个广泛使用的gem,我认为在这两个文件中都有
PageObject
模块就不需要

include PageObject::PagePopulator
因为

include PagePopulator
这就足够了

我想确认我的假设是正确的

在阅读了Module.nesting方法的相关内容以及通过谷歌搜索“重新打开类/模块”查询返回的链接后,我仍然没有找到问题的答案

我将尝试再次描述它

文件_a的内容如下:

require "file_b"
 module Foo
  include Bar
    ...
end
module Foo
 module Bar
   ...
end
require "file_b"
 require "file_c"
  module Foo
   include Bar
     ...
  end
文件内容如下:

require "file_b"
 module Foo
  include Bar
    ...
end
module Foo
 module Bar
   ...
end
require "file_b"
 require "file_c"
  module Foo
   include Bar
     ...
  end
我们不应该使用的解释在哪里 文件_a中包含以下内容:

include Foo::Bar 
而不是

include PagePopulator
include Bar
我以前写的方式是:

include Bar
足够了

如果有,会有什么不同

文件c包含以下内容:

module Bar
    ...
end
这是否意味着从文件c和文件b中包含模块没有区别

文件a、文件b中的模块和文件c中的模块的内容如下:

require "file_b"
 module Foo
  include Bar
    ...
end
module Foo
 module Bar
   ...
end
require "file_b"
 require "file_c"
  module Foo
   include Bar
     ...
  end

如果是这种情况,那么在文件b中使用模块Foo有什么意义呢?

我想你想问的是ruby中常量查找的规则:当你在代码中编写
Bar
时,ruby是如何找到该常量的值的

文件中的东西是不相关的,重要的是里面的东西

module Foo
  ...
end
Bar
的引用将尝试
Foo::Bar
,然后是顶级
::Bar
常量(常量范围是词汇范围)

因此,在先前定义了
Foo::Bar
的情况下

module Foo
  include Foo::Bar
end 

做同样的事情


Module.nesting
方法将显示此查找链。Ruby还将搜索当前打开的类/模块的祖先。有一些陷阱/角落案例,但这些是最基本的

你的文件1和文件2是一样的。你到底为什么希望
包含PagePopulator::PageObject
?塞尔吉奥-对不起-我更正了这一点,我的意思是,为什么
包含PagePopulator::PageObject
而不是
包含PageObject::PagePopulator
?简而言之,你在这里混淆的概念叫做“重新打开类/模块”。你可以用谷歌搜索。我不确定你是否回答了我的问题,或者我不明白答案。文件a需要“文件b”模块Foo包含条。。。结束文件_b:模块Foo模块栏。。。end Where是包含Foo::Bar不需要在文件中使用的解释吗?我目前正在查看Module.nesting,假设这会给我答案,我想您已经解释了关于嵌套的一般规则,ruby doc.org/core-2.2.0/Module.html上的示例#method-c-nesting页面显示了如何找到嵌套的模块/常量。我用更多的描述性细节更新了我最初的帖子