如何使用Ruby的optparse解析不带名称的参数 [英] How to parse an argument without a name with Ruby's optparse

查看:92
本文介绍了如何使用Ruby的optparse解析不带名称的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要像这样解析命令行

I need to parse a command line like

  script.rb <mandatory filename> [options]

使用 optparse .

确定我可以编写一些自定义代码来处理文件名,然后将ARGV传递给optparse,但是也许有更简单的方法来做到这一点?

Sure I can write some custom code to handle the filename, then pass ARGV to optparse, but maybe there's a simpler way to do it?

还有另一种破解此类命令行的方法,那就是将['--mandatory-filename'] + ARGV传递给optparse,然后处理--mandatory-filename选项.

there's another hacky way to parse such a command line, and that is pass ['--mandatory-filename'] + ARGV to optparse, then handle the --mandatory-filename option.

推荐答案

首先使用optparse parse!,然后扫描ARGV并提高ARGV是否为空.像这样:

First parse! with optparse, then scan the ARGV and raise if ARGV is empty. Like so:

op.parse!
filename = ARGV.pop
raise "Need to specify a file to process" unless filename

强制性文件名将不被OptionParser处理,而是留在ARGV中供您使用-如果不存在,请手动提高.

The mandatory filename will not be processed by the OptionParser and will be left for you in ARGV - if it's not there, just raise manually.

这篇关于如何使用Ruby的optparse解析不带名称的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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