Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set class inheritance after class delcaration OR setting class inheritance on const_set class

Tags:

dynamic

ruby

If a class has been previously defined how can I tell it to inherit from a class Parent

For instance:

class Parent
  ..
end

class Klass
  ..
end

Now I want it to inherit from Parent

I cant re-open the class and set it because I will get a class mismatch error

class Klass < Parent
  ..
end

Specifically I am trying to find out how to set the class inheritance on a class im creating through Object.const_set

klass = Object.const_set('Klass', Class.new)

How can I tell Klass to inherit from class Parent?

like image 435
Corban Brook Avatar asked Aug 26 '09 20:08

Corban Brook


People also ask

How can you achieve multiple inheritance in Ruby?

Ruby does not support multiple inheritance. It only supports single-inheritance (i.e. class can have only one parent), but you can use composition to build more complex classes using Modules.

Can parent class inherit from child class?

Inheritance concept is to inherit properties from one class to another but not vice versa. But since parent class reference variable points to sub class objects. So it is possible to access child class properties by parent class object if only the down casting is allowed or possible....

How do you inherit from another class?

Inheritance enables you to create new classes that reuse, extend, and modify the behavior defined in other classes. The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. A derived class can have only one direct base class.

How does class inheritance work C++?

Inheritance between classes. Classes in C++ can be extended, creating new classes which retain characteristics of the base class. This process, known as inheritance, involves a base class and a derived class: The derived class inherits the members of the base class, on top of which it can add its own members.


1 Answers

There is no way to change the superclass of an already existing class.

To specifiy the superclass of a class you're creating dynamically, you simply pass the superclass as an argument to Class.new.

class Parent
end
klass = Class.new(Parent)
klass.superclass #=> Parent

Just as a side note: You're not creating the class with const_set. You're creating it with Class.new. You're simply storing the created class in a constant with const_set. Once const_set is invoked, Class.new has already happened and the superclass cannot be changed anymore.

like image 63
sepp2k Avatar answered Sep 28 '22 07:09

sepp2k