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...]
How to include module B inside of A, so that classes that already include module A will also get methods from module B?
You can’t.
When you
includea mixinMinto a classC, Ruby creates a new class⟦M′⟧whose method table points to the method table of the mixinMand whose superclass is the superclass ofC, then makes this class the new superclass ofC. This is repeated for every mixin that was mixed intoM.Note that this algorithm is run only once, when you mix
MintoC. Modules that getincluded later, will not get considered.