试试这个:
module A
module B
module C
Module.nesting
end
end
end
#=> [A::B::C, A::B, A]
module A::B
module C
Module.nesting
end
end
#=> [A::B::C, A::B]
原因
A
nesting
取决于代码的结构(“词法”),而不是模块的父子关系。因此,我认为任何导致
self
Module.nesting
,注定要失败。
但是,您可以执行以下操作。
def get_nesting(mod)
a = mod.to_s.split('::')
a.size.times.map { |i| Module.const_get(a[0..i].join('::')) }.reverse
end
get_nesting(A) #=> [A]
get_nesting(A::B) #=> [A::B, A]
get_nesting(A::B::C) #=> [A::B::C, A::B, A]
get_nesting(A::B::C).map { |m| m.class }
#=> [Module, Module, Module]
Module#to_s
,这将被归类为胡乱花钱。