在其他模块中包含一个模块

szi*_*mek 7 ruby

module A; def a; end; end
module B; def b; end; end

class C; include A; end

module A; include B; end
class D; include A; end

C.new.b # undefined method error
D.new.b # nil

C.ancestors # [C, A, Object...]
D.ancestors # [D, A, B, Object...]
Run Code Online (Sandbox Code Playgroud)

如何在A中包含模块B,以便已经包含模块A的类也将从模块B获取方法?

Jör*_*tag 2

你不能。

\n\n

当你将includemixinM放入一个类中时C,Ruby 创建一个新类\xe2\x9f\xa6M\xe2\x80\xb2\xe2\x9f\xa7,其方法表指向 mixin 的方法表M,其超类是 的超类C,然后使该类成为 的新超类C。对于混合到的每个 mixin 都会重复此操作M

\n\n

请注意,当您混合MC. 获得的模块included 的模块将不会被考虑。

\n