Do I need to explicitly initialize an object if an initialize method is included in class definition?
The initialize method is useful when we want to initialize some class variables at the time of object creation. The initialize method is part of the object-creation process in Ruby and it allows us to set the initial values for an object.
Definition of initialize transitive verb. : to set (something, such as a computer program counter) to a starting position, value, or configuration.
new , the class will create a new instance of itself. It will then, internally, call the method initialize on the new object. Doing so it will simply pass all the arguments that you passed to new on to the method initialize .
No, Ruby does not call initialize
automatically.
The default implementation of Class#new
looks a bit like this:
class Class
def new(*args, &block)
obj = allocate
obj.initialize(*args, &block)
obj
end
end
[Actually, initialize
is private
by default so you need to use obj.send(:initialize, *args, &block)
.]
So, the default implementation of Class#new
does call initialize
, but it would be perfectly possible (albeit extremely stupid) to override or overwrite it with an implementation that does not.
So, it's not Ruby that calls initialize
, it's Class#new
. You may think that's splitting hairs, because Class#new
is an integral part of Ruby, but the important thing here is: it's not some kind of language magic. It's a method like any other, and like any other method it can be overridden or overwritten to do something completely different.
And, of course, if you don't use new
to create an object but instead do it manually with allocate
, then initialize
wouldn't be called either.
There are some cases where objects are created without calling initialize
. E.g. when dup
ing or clone
ing, initialize_dup
and initialize_clone
are called instead of initialize
(both of which, in turn, call initialize_copy
). And when deserializing an object via, say, Marshal
, its internal state is reconstructed directly (i.e. the instance variables are set reflectively) instead of through initialize
.
Yes, it's called from new
method, which you use to create objects.
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