从命令行运行Ruby库 [英] Run a Ruby library from the command-line

查看:106
本文介绍了从命令行运行Ruby库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚学习了Ruby的基础知识,在使用Python几年后(我仍然在使用Python的一些东西),但我想知道是否有一个成语或黑客来解决这个特殊的问题。



我有一个Ruby脚本,我想能够用 require script_name 我也希望能够从终端运行 ruby​​ script_name.rb ,并将其作为命令行脚本运行。在Python中,这将通过在脚本底部具有以下结构来完成:

 如果__name__ =='__main__': 
#do something here

但是,我似乎不能在Ruby中找到一个等价物。是否有一种方法来检测当前脚本是否正在从命令行运行?也许一些 Kernel :: 方法或东西?理想情况下,我想要的是这样的脚本底部:

 如果from_command_line? 
#do something here
end


解决方案

您可以在ruby中找到类似的功能。


__ FILE __ 当前源文件名。 >

$ 0 包含要执行的脚本的名称。可以指派。


来源: Ruby Quick Ref


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

解决方案

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

这篇关于从命令行运行Ruby库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆