Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When can Ruby classes have multiple superclasses

Why does the following piece of code run as I expect it to run? I was under the impression that a class can only have one superclass and putting something other than the original superclass at the time the class was first defined would raise a type mismatch exception.

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
like image 969
MxLDevs Avatar asked Feb 15 '23 22:02

MxLDevs


1 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 attempt at MI throws the TypeError.

Also it does not change the inheritance of the class. So MyTest.superclass remains Test even after class MyTest < Object

I think it is because Object is the default superclass when a new class is defined. From the docs:

new(super_class=Object) → a_class

So when Object is given as the superclass it is ignored in the mismatch check since it is not known if Object was a user input or the default value.

like image 112
tihom Avatar answered Feb 18 '23 23:02

tihom