Classes can be created dynamically through the use of Class.new
.
# create a new class dynamically
MyClass = Class.new
# instantiate an object of type MyClass
my_class = MyClass.new
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 Class.new
method accepts a Class
which will become the superclass of the dynamically created class.
# dynamically create a class that subclasses another
Staffy = Class.new(Dog)
# instantiate an object of type Staffy
lucky = Staffy.new
lucky.is_a?(Staffy) # true
lucky.is_a?(Dog) # true
The Class.new
method also accepts a block. The context of the block is the newly created class. This allows methods to be defined.
Duck =
Class.new do
def quack
'Quack!!'
end
end
# instantiate an object of type Duck
duck = Duck.new
duck.quack # 'Quack!!'