Does ruby call initialize method automatically?

后端 未结 3 1084

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

3条回答
  •  自闭症患者
    2020-12-09 06: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.

提交回复
热议问题