Ruby:获取同级模块
到目前为止,我知道要获得子模块,应该执行这样的操作:Ruby:获取同级模块,ruby,Ruby,到目前为止,我知道要获得子模块,应该执行这样的操作: module ParentModule module Foo # to be implemented def self.get_bar ::ParentModule::Bar end end module Bar # to be implemented end end 但是,有没有一种方法可以在不引用父模块的情况下获取同级模块?大概是这样的: module Foo def s
module ParentModule
module Foo
# to be implemented
def self.get_bar
::ParentModule::Bar
end
end
module Bar
# to be implemented
end
end
但是,有没有一种方法可以在不引用父模块的情况下获取同级模块?大概是这样的:
module Foo
def self.get_bar
::Bar # doesn't work actually
end
end
因此,mod
的兄弟姐妹是:
kids - [mod]
#=> [ParentModule::Foo]
这比你想象的要简单
module ParentModule
module Foo
def self.get_bar
Bar
end
end
end
您尝试使用的:
命令ruby在顶级作用域中查找此名称。如果省略它,ruby将首先查看当前范围,然后是它的父级,然后是它的父级,一直到顶级
因此,将找不到
ParentModule::Foo::Bar
,但会找到ParentModule::Bar
。您是否尝试忽略::ParentModule
部分?你看到了什么?你尝试了什么?你能澄清你的问题吗?“父母”和“孩子”这两个词都意味着继承,但这里没有继承。我当然试过了。如果我从Foo module def self.get_Bar::Bar end中引用了一个Bar模块,那么我就得到了name错误:未初始化的constantI意味着模块嵌套和引用相邻模块。我认为你“设计过度”了:)@Sergio,我不确定我回答的问题是否设计过度,不幸的是,这不是被问到的问题。我试图识别一个模块的(未知的)“兄弟”模块。是的,你回答了错误的问题。但它应该适用于这个问题。我可以提供我认为更简单的解决方案吗?事实上,别介意我的密码,这也是同一个问题的答案:)谢谢,@Sergio。我忘记了嵌套。
module ParentModule
module Foo
def self.get_bar
Bar
end
end
end