Should I define a main method in my ruby scripts?

RubyMain Method

Ruby Problem Overview


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

Ruby Solutions


Solution 1 - Ruby

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.

Solution 2 - Ruby

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

end

Solution 3 - Ruby

You should put library code in lib/ and executables, which require library code, in bin/. This has the additional advantage of being compatible with RubyGems's packaging method.

A common pattern is lib/application.rb (or preferably a name that is more appropriate for your domain) and bin/application, which contains:

require 'application'
Application.run(ARGV)

Solution 4 - Ruby

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.

Solution 5 - Ruby

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMiniQuarkView Question on Stackoverflow
Solution 1 - RubyAllynView Answer on Stackoverflow
Solution 2 - RubyBenjamin OakesView Answer on Stackoverflow
Solution 3 - RubyRein HenrichsView Answer on Stackoverflow
Solution 4 - RubyAlexander LebedevView Answer on Stackoverflow
Solution 5 - RubyIan TerrellView Answer on Stackoverflow