开发者

Ruby: initialize() vs class body?

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 MyClass.new.

Clearly, initialize() can accept parameters, but is that the only 开发者_如何学Pythondifference?

class MyClass
  puts 'Hello'

  def initialize(params)
    puts 'World'
  end
end


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.


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).


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜