1

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

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

1 回答 1

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

在此处查看现场演示

于 2012-10-08T18:36:45.363 回答