Ruby: initialize() vs class body?

后端 未结 3 1260
日久生厌
日久生厌 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条回答
  •  北海茫月
    2021-02-01 14:56

    Well, initialize gets called by new, whereas the class body gets evaluated on class definition/loading.

    Additionally, try setting an instance variable in the class body or in initialize. You'll notice the latter will belong to the created object, whereas the first will belong to the class instance (hence the name class instance variable).

提交回复
热议问题