反映嵌套命名空间

The*_*Who 5 ruby nested namespaces

我试图找到嵌套命名空间的根类/模块.

这是找到它的最有效方法吗?我不喜欢我转换成字符串.似乎应该有一个更优雅的解决方案.

class Foo
   class Bar
     def parent
        Object.const_get self.class.to_s.split(/::/).first
     end
   end
end

Foo::Bar.new.parent #=> Foo
Run Code Online (Sandbox Code Playgroud)

saw*_*awa 7

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
Run Code Online (Sandbox Code Playgroud)