首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何动态更改Ruby中的继承

如何动态更改Ruby中的继承
EN

Stack Overflow用户
提问于 2010-06-27 10:24:18
回答 7查看 11.9K关注 0票数 13

我想动态地为Ruby中的类指定父类。请考虑以下代码:

代码语言:javascript
复制
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

ParentChild类定义都没有指定父类,因此它们都是从对象继承的。我的第一个问题是:我需要在Agent.hook_up中做什么才能使Parent成为Child的超类(例如,Child对象可以继承'bar‘方法)。

我的第二个问题是:我是否需要将第一个参数传递给Agent.hook_up,还是hook_up方法可以以编程方式确定调用它的类?

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2010-06-27 11:57:00

约书亚已经给出了一个很好的选择列表,但是要回答你的问题:在用ruby创建类之后,您不能更改类的超类。这根本不可能。

票数 7
EN

Stack Overflow用户

发布于 2010-06-27 10:56:59

也许你在找这个

代码语言:javascript
复制
Child = Class.new Parent do
  def foo
    "foo"
  end
end

Child.ancestors   # => [Child, Parent, Object, Kernel]
Child.new.bar     # => "bar"
Child.new.foo     # => "foo"

由于父类是Class.new的一个参数,所以可以与其他类交换它。

我以前在编写某些测试时使用过这种技术。但我很难想出许多好的借口来做这样的事。

我怀疑你真正想要的是一个模块。

代码语言:javascript
复制
class Agent
  def self.hook_up(calling_class, desired_parent_class)
    calling_class.send :include , desired_parent_class
  end
end

module Parent
  def bar
    "bar"
  end
end

class Child
  def foo
    "foo"
  end

  Agent.hook_up(self, Parent)
end

Child.ancestors   # => [Child, Parent, Object, Kernel]
Child.new.bar     # => "bar"
Child.new.foo     # => "foo"

不过,当然,根本不需要代理

代码语言:javascript
复制
module Parent
  def bar
    "bar"
  end
end

class Child
  def foo
    "foo"
  end

  include Parent
end

Child.ancestors   # => [Child, Parent, Object, Kernel]
Child.new.bar     # => "bar"
Child.new.foo     # => "foo"
票数 25
EN

Stack Overflow用户

发布于 2010-06-28 01:05:54

只有Ruby1.9:(1.8类似,但使用RCLASS(self)->super代替)

代码语言:javascript
复制
require 'inline'
class Class
    inline do |builder|

        builder.c %{            
            VALUE set_super(VALUE sup) {
                RCLASS(self)->ptr->super = sup;
                return sup;
            }
        }

        builder.c %{
            VALUE get_super() {
                return RCLASS(self)->ptr->super;
            }
        }

    end


J = Class.new
J.set_super(Class.new)
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3127069

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档