我应该在 ruby 脚本中定义 main 方法吗?
在 Python 中,模块没有有 main 函数,但通常的做法是使用以下习惯用法:
def my_main_function():
... # some code
if __name__=="__main__": # program's entry point
my_main_function()
我知道 Ruby 没有有 a main 方法也可以,但是我应该遵循某种最佳实践吗? 我应该将我的方法命名为 main
还是其他名称?
有关主要方法的维基百科页面并没有真正帮助我。
顺便说一句,我还在 python 中看到了以下习惯用法:
def my_main_function(args=[]):
... # some code
if __name__=="__main__": # program's entry point
import sys
sys.exit(my_main_function(sys.argv))
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))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我通常使用
所以是的,你可以。 这仅取决于您在做什么。
I usually use
So yes, you can. It just depends on what you are doing.
我一直发现
$PROGRAM_NAME
比使用$0
更具可读性。 当我看到这样的“类似 Perl”的全局变量时,有一半的时间我必须去查找它们。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.您应该将库代码放在 lib/ 中,将需要库代码的可执行文件放在 bin/ 中。 这还有一个额外的优点,就是与 RubyGems 的打包方法兼容。
常见的模式是 lib/application.rb (或者最好是更适合您的域的名称)和 bin/application,其中包含:
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:
我个人的经验法则是:当行数
超过 5 行时,我将其提取到
main
函数中。 这对于 Python 和 Ruby 代码都适用。 如果没有该代码,看起来结构就会很差。My personal rule of thumb is: the moment
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.不。
为什么要增加额外的复杂性却没有真正的好处呢? Rubyists 没有使用它的约定。
我会等到您第二次需要使用它(这可能发生的频率比您想象的要少),然后重构它以使其可重用,这可能会涉及像上面这样的构造。
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.