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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With