如何在另一个类中动态创建一个类并为其添加继承?

时间:2012-10-08 18:34:11

标签: ruby

其他SO答案显示了如何创建具有继承的类,是的, 但我也需要它成为另一个类的子类。

class Wall
  def initialize
    # i need a Brick class here with inheritance from Stone
  end
end

1 个答案:

答案 0 :(得分:2)

尝试这样的事情:

class Stone

end

class Wall
    def initialize
        brick = Class.new Stone
        self.class.const_set :Brick, brick
    end
end

puts 'before initialize'
p Wall.constants
p Wall::Brick.ancestors rescue nil

puts 'after initialize'
Wall.new
p Wall.constants
p Wall::Brick.ancestors

请参阅live demo here