2

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

What is the difference 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?

sepp2k
  • 363,768
  • 54
  • 674
  • 675
Dave
  • 723
  • 7
  • 19
  • initialize is the standard way because it is called automatically on new objects. Maybe if you posted a complete example of where you saw main used instead, we could see what you're talking about? – Sean DeNigris Jan 01 '11 at 21:52
  • 1
    I have never seen `main` used or recommended in Ruby as a method. Are you perhaps referring to the [top-level context object named "main"](http://stackoverflow.com/questions/917811/what-is-main-in-ruby)? – Phrogz Jan 01 '11 at 22:19
  • I figured out the problem, which was with my understanding of what #new did. I was looking at a game engine that used a main function to load scenes in the main loop. I was missing $scene.main part, which explains everything. – Dave Jan 02 '11 at 02:09

2 Answers2

6

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.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
0

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.

DigitalRoss
  • 143,651
  • 25
  • 248
  • 329