49

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))
MiniQuark
  • 40,659
  • 30
  • 140
  • 167

5 Answers5

77

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
  • 19,710
  • 16
  • 55
  • 68
51

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
9

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)
Rein Henrichs
  • 14,632
  • 1
  • 42
  • 51
  • This is an excellent answer. Place your script in ./bin and add `#!/usr/bin/env ruby` to the top. Then make it executable (chmod +x) and you have something that's well organized and easy to understand. – mastaBlasta Mar 15 '17 at 18:24
4

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.

Alexander Lebedev
  • 5,750
  • 1
  • 18
  • 29
-1

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
  • 10,280
  • 10
  • 41
  • 65