Does ruby call initialize method automatically?

后端 未结 3 1086

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

3条回答
  •  轮回少年
    2020-12-09 06:22

    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.

提交回复
热议问题