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

Ruby 如何在另一个类中动态创建一个类并向其添加继承?,ruby,Ruby,其他答案显示了如何使用继承创建类,是的, 但我也需要它是另一个类的子类 class Wall def initialize # i need a Brick class here with inheritance from Stone end end 试着这样做: class Stone end class Wall def initialize brick = Class.new Stone self.class.const_set

其他答案显示了如何使用继承创建类,是的, 但我也需要它是另一个类的子类

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

试着这样做:

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

看,你的工作真有魅力!我的导师今晚会很高兴:)我现在可以回忆起他说的是
const_set
:)谢谢!