San Tiago
San Tiago

Reputation: 189

How to dynamically create a class inside another class and add inheritance to it?

other SO answers shows how to create classes with inheritance, yes, but i also need it to be a subclass of another class.

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

Upvotes: 1

Views: 76

Answers (1)

user904990
user904990

Reputation:

try something like this:

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

See live demo here

Upvotes: 2

Related Questions