Ruby Language Classes New, allocate, and initialize

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 Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

In many languages, new instances of a class are created using a special new keyword. In Ruby, new is also used to create instances of a class, but it isn't a keyword; instead, it's a static/class method, no different from any other static/class method. The definition is roughly this:

class MyClass
   def self.new(*args)
     obj = allocate
     obj.initialize(*args) # oversimplied; initialize is actually private
     obj
   end
end

allocate performs the real 'magic' of creating an uninitialized instance of the class

Note also that the return value of initialize is discarded, and obj is returned instead. This makes it immediately clear why you can code your initialize method without worrying about returning self at the end.

The 'normal' new method that all classes get from Class works as above, but it's possible to redefine it however you like, or to define alternatives that work differently. For example:

class MyClass
  def self.extraNew(*args)
    obj = allocate
    obj.pre_initialize(:foo)
    obj.initialize(*args)
    obj.post_initialize(:bar)
    obj
  end
end


Got any Ruby Language Question?