11

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

3 Answers 3

26

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Do you want to mention how a derived class interacts with its parent's initialize?
@Jorge what do you mean by overwrite? can you bit clarify this?
@Priti: Ruby has so-called open classes, it allows you to overwrite an existing method with a new implementation.
@WayneConrad: my point is that initialize is nothing special, it's just a method like any other. So, super works exactly the same as it always does.
@JörgWMittag ohh!yes it is like that.
1

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

Comments

1

It depends on your definition of "explicit". Usually you need to, even if there are no arguments:

object = MyClass.new(...)

In some cases there are factory methods that produce instances you can use, creating a form of implicit initialization:

object = MyClass.factory_method(...)

This would have the effect of calling MyObject.new internally.

There are some libraries which have rather unusual method signatures, like:

object = MyClass(...)
object = MyClass[...]

The effect is the same, as these might look odd but are just method calls.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.