Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we define `#initialize` instead of `::new`

In Ruby, when making a new class, we will define the constructor method like so:

class Thing
  def initialize
     do_stuff
  end
end

However, when actually making an instance of the object, we find ourselves not calling initialize on the instance but new on the class.

That being the case, why don't we instead define ::new?

class Thing
   def self.new
     do_stuff
   end
end

Is there something ::new does beind the scenes that initalize doesn't define? Are those two different at all? Would defining ::new work? Or is it just that def initialize is shorter (not) than def self.new?

I'm thinking there must be a good reason for the disparity.

like image 801
Jonathan Allard Avatar asked Jan 14 '13 22:01

Jonathan Allard


1 Answers

New allocates space for the new object and creates it. It then calls the Objects initialize method to create a new Object using the allocated memory. Usually, the only part you want to customize is the actual creation, and are happy to leave the behind memory allocation to the Object.new method, so you write an initialize method. What new is doing under the hood looks something like this (except in C):

 class Object
    def self.new(*args, &block)
        object = allocate
        object.send(:initialize, *args, &block)
        return object
    end
 end

So when you call Object.new, what actually happens is:

1) Memory is allocated 2) The objects initialize method is called.

like image 78
Abraham P Avatar answered Oct 13 '22 00:10

Abraham P