我正在尝试找到嵌套命名空间的根类/模块。
这是最有效的查找方式吗?我不喜欢将其转换为字符串。似乎应该有更优雅的解决方案。
class Foo
class Bar
def parent
Object.const_get self.class.to_s.split(/::/).first
end
end
end
Foo::Bar.new.parent #=> Foo
我正在尝试找到嵌套命名空间的根类/模块。
这是最有效的查找方式吗?我不喜欢将其转换为字符串。似乎应该有更优雅的解决方案。
class Foo
class Bar
def parent
Object.const_get self.class.to_s.split(/::/).first
end
end
end
Foo::Bar.new.parent #=> Foo
有一个叫做Module.nesting
的东西。
module Foo
module Bar
module Baz
p Module.nesting # => [Foo::Bar::Baz, Foo::Bar, Foo]
p Module.nesting.last # => Foo
end
end
end
Foo::Bar::Baz.class_eval{ Module.nesting } # => []
,Foo::Bar::Baz.module_eval{ Module.nesting } # => []
,以及Foo::Bar.instance_eval{ Module.nesting } # => []
。 - rudolph9嵌套
方法是像__dir__
,binding
这样的少数几种方法之一,其中文字环境很重要。即使其他结构通常是等效的,也不能用其他结构替换它。 - sawa