Ruby: initialize() vs class body?

后端 未结 3 1265
日久生厌
日久生厌 2021-02-01 14:12

In Ruby, what is the difference between putting code in an initialize() method rather than directly in the class body? Both appear to be executed when calling

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-01 14:45

    if you write a code in class body it will be executed when ruby load that class, the loading can be happen only once. And initialize will be executed only when you make an instance of class, and it will be executed every time when you call new to class.

    now when you do MyClass.new ruby loads class MyClass it will look for class in memory if it is not then load that class, then call its new method to create instanc

提交回复
热议问题