New allocate and initialize

suggest change

In many languages, new instances of a class are created with a special new keyword. In Ruby, new is not a keyword. It is a class method. The definition is roughly this:

class MyClass
   def self.new(*args)
     obj = allocate
     obj.send(:initialize, *args) # initialize is private
     obj
   end
end

allocate creates 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.send(:initialize, *args)
    obj.post_initialize(:bar)
    obj
  end
end

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents