Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ruby call initialize method automatically?

Tags:

ruby

Do I need to explicitly initialize an object if an initialize method is included in class definition?

like image 959
OneZero Avatar asked Apr 26 '13 21:04

OneZero


People also ask

What does initialize method do in Ruby?

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.

What is def initialize?

Definition of initialize transitive verb. : to set (something, such as a computer program counter) to a starting position, value, or configuration.

What does .NEW do in Ruby?

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 .


2 Answers

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 duping or cloneing, 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.

like image 195
Jörg W Mittag Avatar answered Oct 14 '22 16:10

Jörg W Mittag


Yes, it's called from new method, which you use to create objects.

like image 39
Sergio Tulentsev Avatar answered Oct 14 '22 16:10

Sergio Tulentsev