When Ruby Classes Have Multiple Superclasses

Why is the following code fragment executing, as I expect it to run? I got the impression that a class can have only one superclass and put something different from the original superclass during class definition, would cause an exception of type mismatch.

class Test
end

class MyTest < Test

  def run
    p 'my test'
  end
end

class MyTest < Object

  def run
    p 'redefine my test'
  end
end

MyTest.new.run

Result

redefine my test
+4
source share
2 answers

It works for me (Ruby 1.9.2 and 1.9.3) only if the second class declaration is inherited from Object. Any other MI attempt throws TypeError.

Also, it does not change the inheritance of the class. So, it MyTest.superclassremains Testeven afterclass MyTest < Object

, , Object superclass . docs:

new(super_class=Object) → a_class

, Object superclass, , , Object .

+5

. Ruby MI ( . ).

Ruby. , "TypeError: .." (Ruby 1.9.2, 1.9.3 ).

, MyTest.superclass, , : , #superclass , .

, , MI:

class A
   def a; "a"; end
end
class B
   def b; "b"; end
end
class C < A
end
# This may raise said TypeError, but if it does not then ..
class C < B
end
# .. either this will work
C.new.a
# .. /or possibly/ this will work
C.new.b
# If the redefinition added MI then /both/ would work.
# If such an implementation is found, please let me know!

( , TypeError.)

+3

All Articles