仅当从命令行调用脚本时才运行代码
因此,当我从命令行调用我的脚本时,我希望它接受一个 int 并对该值执行某些操作:
ruby script.rb
puts ARGV[0], etc...
但是,每当加载或需要脚本而不是从命令行调用脚本时,我想完全跳过这部分代码。如何检测脚本是否已通过命令行调用或刚刚加载?谢谢!
So when I call my script from the command line, I want it to take in an int and do something with the value:
ruby script.rb
puts ARGV[0], etc...
However, whenever the script is loaded or required and not called from command line, I want to completely skip this part of the code. How can I detect whether the script has been called via command line, or just loaded? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通常将其放在脚本的底部:
因为我喜欢在文件顶部看到主要操作,所以我通常将
def run!
作为文件中的第一个方法,然后然后用以下内容结束文件:It is common to put this at the bottom of your script:
Because I like to see the main action at the top of my file, I usually put a
def run!
as the first method in the file and then end the file with: