问题
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))
回答1:
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.
回答2:
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
回答3:
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)
回答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.
回答5:
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.
来源:https://stackoverflow.com/questions/582686/should-i-define-a-main-method-in-my-ruby-scripts