python `if __name__ == '__main__'` 等价于 Ruby
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2249310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
`if __name__ == '__main__'` equivalent in Ruby
提问by Imagist
I am new to Ruby. I'm looking to import functions from a module that contains a tool I want to continue using separately. In Python I would simply do this:
我是 Ruby 的新手。我希望从包含我想继续单独使用的工具的模块导入函数。在 Python 中,我会简单地这样做:
def a():
...
def b():
...
if __name__ == '__main__':
a()
b()
This allows me to run the program or import it as a module to use a()
and/or b()
separately. What's the equivalent paradigm in Ruby?
这允许我运行程序或将其作为模块导入a()
和/或b()
单独使用。Ruby 中的等效范例是什么?
回答by Matchu
From the Ruby I've seen out in the wild (granted, not a ton), this is not a standard Ruby design pattern. Modules and scripts are supposed to stay separate, so I wouldn't be surprised if there isn't really a good, clean way of doing this.
从我在野外看到的 Ruby(当然,不是很多)来看,这不是标准的 Ruby 设计模式。模块和脚本应该保持分开,所以如果没有真正好的、干净的方法来做到这一点,我不会感到惊讶。
EDIT:Found it.
编辑:找到了。
if __FILE__ == if caller.length == 0
# do stuff
end
foo()
bar()
end
But it's definitely not common.
但这绝对不常见。
回答by uKolka
If stack trace is empty, we can start executing to the right and left. I don't know if that's used conventionally or unconventionally since I'm into Ruby for about a week.
如果堆栈跟踪为空,我们可以开始向右和向左执行。我不知道这是常规使用还是非常规使用,因为我使用 Ruby 大约一个星期。
#!/usr/bin/ruby
if caller.length == 0
puts "Main script"
end
puts "Test"
Proof of concept:
概念证明:
file: test.rb
文件:test.rb
#!/usr/bin/ruby -I .
require 'test.rb'
puts "Shmest"
file: shmest.rb
文件:shmest.rb
$ ./shmest.rb
Test
Shmest
$ ./test.rb
Main script
Test
Usage:
用法:
if $PROGRAM_NAME == __FILE__
foo()
bar()
end