问题:相当于Ruby中的`if __name__ ==’__main __’`

我是Ruby的新手。我正在从包含要继续单独使用的工具的模块中导入函数。在Python中,我只需执行以下操作:

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

这使我可以运行程序或将其导入为模块使用a()和/或b()单独使用。Ruby中的等效范例是什么?

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:

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?


回答 0

从我在野外看到的Ruby(当然,不是一吨)来看,这不是标准的Ruby设计模式。模块和脚本应该保持独立,因此,如果没有真正好的清洁方法,我也不会感到惊讶。

编辑: 找到了。

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

但这绝对不常见。

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.


回答 1

如果堆栈跟踪为空,我们可以从左右开始执行。我不知道这是常规使用还是非常规使用,因为我进入Ruby大约一周了。

if caller.length == 0
  # do stuff
end

概念证明:

文件:test.rb

#!/usr/bin/ruby                                                                 

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

puts "Test"

文件:shmest.rb

#!/usr/bin/ruby -I .                                                            

require 'test.rb'

puts "Shmest"

用法:

$ ./shmest.rb 
Test
Shmest

$ ./test.rb
Main script
Test

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

回答 2

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

Rubocop首选:

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

is preferred by Rubocop over this:

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。