Run a Ruby library from the command-line

2019-03-12 15:42发布

I've just learned the basics of Ruby after being very happy with Python for several years (I'm still using Python for some things), but I'd like to know if there's an idiom or hack to solve this particular problem.

I have a Ruby script which I'd like to be able to do require script_name with, but I'd also like to be able to run ruby script_name.rb from the terminal and have it run as a command line script. In Python this would be done by having the following structure at the bottom of the script:

if __name__ == '__main__':
    # do something here

However, I can't seem to find an equivalent in Ruby. Is there a way of detecting whether or not the current script is being run from the command-line? Maybe some Kernel:: method or something? Ideally what I'd like is something like this at the bottom of the script:

if from_command_line?
  # do something here
end

3条回答
戒情不戒烟
2楼-- · 2019-03-12 15:51

You can find a similar functionality in ruby.

__FILE__ the current source file name.

$0 Contains the name of the script being executed. May be assignable.

source: Ruby Quick Ref

查看更多
仙女界的扛把子
3楼-- · 2019-03-12 16:07

You want to use:

if __FILE__ == $0
  # do stuff
end

__FILE__ is the source file name and $0 is the name of the script currently being executed.

查看更多
一纸荒年 Trace。
4楼-- · 2019-03-12 16:17

While

if __FILE__ == $0
  Foo.run
end

is the common approach, I'm currently using

if File.identical?(__FILE__, $0)
  Foo.run
end

because programs like ruby-prof can make $0 not equal __FILE__ even when you use --replace-progname.

查看更多
登录 后发表回答