Ruby Language Classes Dynamic class creation

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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!!'


Got any Ruby Language Question?