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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-10 01:21:44

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/1337439/set-class-inheritance-after-class-delcaration-or-setting-class-inheritance-on-co

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!