如何检查Ruby文件是通过"require"还是"load"导入的,而不是简单地从命令行执行?
例如:
foo.rb的内容:
puts "Hello"
Run Code Online (Sandbox Code Playgroud)
bar.rb的内容
require 'foo'
Run Code Online (Sandbox Code Playgroud)
输出:
$ ./foo.rb
Hello
$ ./bar.rb
Hello
Run Code Online (Sandbox Code Playgroud)
基本上,我想调用bar.rb不执行puts调用.
if __FILE__ != $0 #if the file is not the main script which is running
quit #then quit
end
Run Code Online (Sandbox Code Playgroud)
把它放在foo.rb中的所有代码之上
将 foo.rb 更改为:
if __FILE__ == $0
puts "Hello"
end
Run Code Online (Sandbox Code Playgroud)
这会检查__FILE__- 当前 ruby 文件$0的名称 - 正在运行的脚本的名称。
| 归档时间: |
|
| 查看次数: |
553 次 |
| 最近记录: |