ruby – 如何将模块包含在类中

如何获取类中包含的模块数组,不包括那些通过继承传入的模块?

请注意,祖先< =&gt ;, included_modules不起作用,因为它们的结果不区分包含在超类中预先添加的模块的模块.换句话说,他们无法区分以下两种情况:
> M前置于B的超类

class A; end
class B < A; end
module M; end
A.prepend M

B.ancestors # => [B, M, A, Object, Kernel, BasicObject]
B <=> M # => -1
B.included_modules # => [M, Kernel]

> M包含在B中

class A; end
class B < A; end
module M; end
B.include M

B.ancestors # => [B, M, A, Object, Kernel, BasicObject]
B <=> M # => -1
B.included_modules # => [M, Kernel]

最佳答案

mixed_in  = B.included_modules[0...-B.superclass.included_modules.size]
prepended = B.ancestors.take_while { |ancestor| ancestor != B }
included  = mixed_in - prepended
点赞