如何列出Ruby类中包含的模块?

您如何列出Ruby中类层次结构中特定类中包含的模块? 像这样的东西:

module SomeModule end class ParentModel < Object include SomeModule end class ChildModel  [SomeModule] p ChildModel.included_modules(false) #=> [] 

列出祖先会使模块在树中显得更高:

 p ChildModel.ancestors #=> [ChildModel, ParentModel, SomeModule, Object, Kernel] 

据我了解你的问题,这是你正在寻找的东西:

 class Class def mixin_ancestors(include_ancestors=true) ancestors.take_while {|a| include_ancestors || a != superclass }. select {|ancestor| ancestor.instance_of?(Module) } end end 

但是,我并不完全了解您的测试用例:为什么SomeModule被列为SomeModule的包含模块,即使它实际上并未包含在ChildModel但在ParentModel ? 相反,为什么Kernel 被列为包含模块,即使它在祖先链中与SomeModule一样SomeModule ? 该方法的布尔参数是什么意思?

(请注意,布尔参数总是设计不好:一个方法应该完成一件事。如果它采用布尔参数,它根据定义做件事,一件是参数为真,另一件是参数是假。或者,如果它只做一件事,那么这只能意味着它忽略了它的论点,在这种情况下它不应该从它开始。)