2011-03-24 87 views
5

我想找到嵌套命名空間的根類/模塊。反映在嵌套命名空間

這是找到它的最有效的方法嗎?我不喜歡我轉換爲字符串。似乎應該有一個更優雅的解決方案。

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

Foo::Bar.new.parent #=> Foo 

回答

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 
+0

太好了,非常感謝你。 – 2011-03-24 20:04:44

+0

@sawa爲什麼以下不工作? 'Foo :: Bar :: Baz.class_eval {Module.nesting}#=> []'也不是'Foo :: Bar :: Baz.module_eval {Module.nesting}#=> []'也不是'Foo :: Bar。 instance_eval {Module.nesting}#=> []' – rudolph9 2016-12-09 16:55:26

+0

@ rudolph9'嵌套'方法是'__dir__',''binding''這樣的幾個方法之一,在這裏文字環境很重要。即使它們通常是等效的,也不能用其他結構代替它。 – sawa 2016-12-12 04:16:55