Ruby Language Classes Dynamic class creation


Classes can be created dynamically through the use of

# create a new class dynamically
MyClass =

# instantiate an object of type MyClass
my_class =

In the above example, a new class is created and assigned to the constant MyClass. This class can be instantiated and used just like any other class.

The method accepts a Class which will become the superclass of the dynamically created class.

# dynamically create a class that subclasses another
Staffy =

# instantiate an object of type Staffy
lucky =
lucky.is_a?(Staffy) # true
lucky.is_a?(Dog)    # true

The method also accepts a block. The context of the block is the newly created class. This allows methods to be defined.

Duck = do
    def quack

# instantiate an object of type Duck
duck =
duck.quack # 'Quack!!'