如何在Ruby中动态更改继承 [英] How to dynamically alter inheritance in Ruby
问题描述
我想为Ruby中的类动态指定父类.考虑以下代码:
I would like to dynamically specify the parent class for a class in Ruby. Consider this code:
class Agent
def self.hook_up(calling_class, desired_parent_class)
# Do some magic here
end
end
class Parent
def bar
puts "bar"
end
end
class Child
def foo
puts "foo"
end
Agent.hook_up(self, Parent)
end
Child.new.bar
Parent
和Child
类定义均未指定父类,因此它们都继承自Object.我的第一个问题是:为了使Parent
成为Child
的超类,在Agent.hook_up
中我需要做什么(例如,Child
对象可以继承'bar'方法).
Neither the Parent
nor the Child
class definition specifies a parent class, so they both inherit from Object. My first question is: what would I need to do in Agent.hook_up
in order to make Parent
the superclass of Child
(so for example Child
objects can inherit the 'bar' method).
我的第二个问题是:我需要将第一个参数传递给Agent.hook_up
,还是hook_up
方法可以通过编程方式确定调用它的类的某种方式?
My second question is: do I need to pass the first argument to Agent.hook_up
, or is there some way the hook_up
method can programmatically determine the class from which it was called?
推荐答案
约书亚(Joshua)已经为您提供了大量替代方案,但要回答您的问题:创建类后,您无法更改类的超类在红宝石中.根本不可能.
Joshua has already given you a great list of alternatives, but to answer your question: You can't change the superclass of a class after the class has been created in ruby. That's simply not possible.
这篇关于如何在Ruby中动态更改继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!