开发者

main vs initialize in Ruby

Okay, so I've looked through a couple of my ruby books and done some googling to no avail.

What is the di开发者_运维问答fference between main and initialize in Ruby? I've seen code that uses

class Blahblah  
  def main  
    # some logic here  
  end  
  # more methods...
end 

and then calls it using Blahblah.new.

Isn't new reserved only for initialize? if not, then what's the difference between the two?


Class#new calls alloc on the class and then initialize on the created object. It does not call main.

The method name main has no special meaning in ruby's standard library. So unless you're inheriting from a class, which defines new or initialize in such a way, that main will be called, main will not be called automatically in any way.


See class Class


Look up class Class in your Ruby documentation.

You will find a public instance method called new.

All classes are instances of Class, so they all have a class method self.new. As it happens, this method calls allocate to create the class and then, if an initialize instance method is defined for the new class, it calls it, and forwards its (i.e., new's) arguments.

There isn't anything special about main.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜