views:

797

answers:

4

In python, a module doesn't have to have a main function, but it is common practice to use the following idiom:

def my_main_function():
    ... # some code

if __name__=="__main__":  # program's entry point
    my_main_function()

I know Ruby doesn't have to have a main method either, but is there some sort of best practice I should follow? Should I name my method main or something?

The Wikipedia page about main methods doesn't really help me.


As a side-note, I have also seen the following idiom in python:

def my_main_function(args=[]):
    ... # some code

if __name__=="__main__":  # program's entry point
    import sys
    sys.exit(my_main_function(sys.argv))
+12  A: 

I usually use

if __FILE__ == $0
  x = SweetClass.new(ARGV)
  x.run # or go, or whatever
end

So yes, you can. It just depends on what you are doing.

Allyn
This is good advice - this way, your file is usable both as a standalone executable and as a library
Paul Betts
+1 cool. I had a more convoluted way the boiled down to basically the same thing. I'll replace it with this.
Dave Ray
The conditional doesn't work as desired if you're using ruby-prof or the like.
Andrew Grimm
A: 

No.

Why add an extra layer of complexity for no real benefit? There's no convention for Rubyists that uses it.

I would wait until the second time you need to use it (which will probably happen less often than you think) and then refactor it so that it's reusable, which will probably involve a construct like the above.

Ian Terrell
A: 

My personal rule of thumb is: the moment

if __FILE__ == $0
    <some code>
end

gets longer than 5 lines, I extract it to main function. This holds true for both Python and Ruby code. Without that code just looks poorly structured.

Alex Lebedev
+2  A: 

I've always found $PROGRAM_NAME more readable than using $0. Half the time that I see the "Perl-like" globals like that, I have to go look them up.


if __FILE__ == $PROGRAM_NAME
  # Put "main" code here
end