Ruby: initialize() vs class body?

后端 未结 3 1264
日久生厌
日久生厌 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 15:06

    Try to create two instances of MyClass

    a = MyClass.new
    b = MyClass.new
    

    to see the difference:

    Hello

    World

    World

    Code in the class body execute only once - when ruby loads the file. initialize() executes every time you create a new instance of your class.

提交回复
热议问题