Essentially three things happen when you instantiate a class in Ruby:

  1. Space is allocated for the new object of the class to be created.
  2. An initializer is called to set up intsance variables, for example.
  3. An instance of the created object of the class is returned.

A good way to demonstrate this would be through an example. So let’s say we have a class Country that we want to instantiate, but instead of going the usual route and doing something like Country.new, we’ll implement our own version of new to mimic what new does under the hood. fresh is what we’ll call our version of new.

Our implementation would then look something like this:

class Country 
  def self.fresh(name, capital)
    instance = allocate                         # 1. Allocate space for a new object 
    instance.custom_initializer(name, capital)  # 2. Call initializer
    instance                                    # 3. Return instance of Country
  end

  def custom_initializer(name, capital)
    @name = name
    @capital = capital
  end
end

p Country.fresh("Ghana", "Accra")
# => #<Country:0x000000010c5e23f8 @name="Ghana", @capital="Accra">

The documentation for allocatereads:

Allocates space for a new object of class’s class and does not call initialize on the new instance. The returned object must be an instance of class.

This appears to be the most important step in the instantiation process. Knowing that you can hack object instantiation presents a whole set of possibilities that amplify the dynamism of the Ruby programming language.

    Powered By ConvertKit
    Consider subscribing to my newsletter for a chance to get my upcoming eBook collection of rad Ruby idioms, tips & tricks or follow me on Twitter to explore Ruby, JavaScript and web technologies.