Search code examples
rubymain-method

Should I define a main method in my ruby scripts?


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

Solution

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