Should I define a main method in my ruby scripts?

2019-01-30 13:55发布

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

5条回答
Lonely孤独者°
2楼-- · 2019-01-30 14:18

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)
查看更多
爷的心禁止访问
3楼-- · 2019-01-30 14:26

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.

查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-01-30 14:31

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楼-- · 2019-01-30 14:34

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.

查看更多
叼着烟拽天下
6楼-- · 2019-01-30 14:38

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
查看更多
登录 后发表回答