New allocate and initialize

suggest change

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) # oversimplified; 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

Feedback about page:

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



Table Of Contents