I thought that Ruby only allowed single inheritance besides mixin. However, when I have class Square
that inherits class Thing
, Thing
in t
Multiple inheritance - This is absolutely not possible in ruby not even with modules.
multilevel inheritance - This is what is possible even with the modules.
Why ?
Modules acts as an absolute superclasses to the class that includes them.
Ex1 :
class A
end
class B < A
end
This is a normal inheritance chain, and you can check this by ancestors.
B.ancestors => B -> A -> Object -> ..
Inheritance with Modules -
Ex2 :
module B
end
class A
include B
end
inheritance chain for above example -
B.ancestors => B -> A -> Object -> ..
Which is exactly same as a Ex1. That means all the methods in module B can override the methods in A, And it acts as a real class inheritance.
Ex3 :
module B
def name
p "this is B"
end
end
module C
def name
p "this is C"
end
end
class A
include B
include C
end
A.ancestors => A -> C -> B -> Object -> ..
if you see the last example even though two different modules are included they are in a single inheritance chain where B is a superclass of C, C is a superclass of A.
so,
A.new.name => "this is C"
if you remove the name method from module C, above code will return "this is B". which is same as inheriting a class.
so,
At any point there is only one multilevel inheritance chain in ruby, which nullifies having multiple direct parent to the class.