Software Writer

striving to write software, well

Overriding Constructors in Ruby

July 29, 2021

Everything in Ruby is an object, including the class. When you create a new class, you are basically creating an instance of class Class. Ruby even allows you to override the new method on a class, allowing you to customize the creation of all objects.

class Person
  # person-specific code

When Ruby encounters the above code, it creates an instance of type Class. It then assigns this object to a global constant named Person.

When you call to create a new person, the #new method on the Class is called, by default. However, like everything in Ruby, you can override it.

class Class
  alias create new

  def new(*args)
    puts "Creating a new #{}"

class Person; end

ak =

# Creating a new Person
# #<Person:0x00007fde9e869280>
puts ak

Knowing that classes are instances of Class allows you to dynamically create classes on the fly.

Person = do
  def greet

ak =
puts ak.greet    # hello