‘ if__ name__ = =’__main__’’在 Ruby 中等效

我是鲁比的新手。我希望从一个模块中导入函数,该模块包含一个我希望继续单独使用的工具。在 Python 中,我只需要这样做:

def a():
...
def b():
...
if __name__ == '__main__':
a()
b()

这允许我运行程序或将其作为模块导入,以分别使用 a()和/或 b()。Ruby 中的等效范例是什么?

23330 次浏览

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.

EDIT: Found it.

if __FILE__ == $0
foo()
bar()
end

But it's definitely not common.

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.

if caller.length == 0
# do stuff
end

Proof of concept:

file: test.rb

#!/usr/bin/ruby


if caller.length == 0
puts "Main script"
end


puts "Test"

file: shmest.rb

#!/usr/bin/ruby -I .


require 'test.rb'


puts "Shmest"

Usage:

$ ./shmest.rb
Test
Shmest


$ ./test.rb
Main script
Test
if $PROGRAM_NAME == __FILE__
foo()
bar()
end

is preferred by Rubocop over this:

if __FILE__ == $0
foo()
bar()
end