使用ruby的OptionParser解析子命令 [英] Using ruby's OptionParser to parse sub-commands

查看:123
本文介绍了使用ruby的OptionParser解析子命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够使用ruby的OptionParser来解析形式的子命令

I'd like to be able to use ruby's OptionParser to parse sub-commands of the form

COMMAND [GLOBAL FLAGS] [SUB-COMMAND [SUB-COMMAND FLAGS]]

喜欢:

git branch -a
gem list foo

我知道我可以切换到其他选项解析器库(例如Trollop),但是我想从OptionParser中学习如何执行此操作,因为我想更好地学习该库.

I know I could switch to a different option parser library (like Trollop), but I'm interested in learning how to do this from within OptionParser, since I'd like to learn the library better.

有什么提示吗?

推荐答案

弄清楚了.我需要使用OptionParser#order!.它将解析ARGV开头的所有选项,直到找到一个非选项(不是选项参数),然后从ARGV中删除它处理的所有内容,然后退出.

Figured it out. I need to use OptionParser#order!. It will parse all the options from the start of ARGV until it finds a non-option (that isn't an option argument), removing everything it processes from ARGV, and then it will quit.

所以我只需要做类似的事情:

So I just need to do something like:

global = OptionParser.new do |opts|
  # ...
end
subcommands = { 
  'foo' => OptionParser.new do |opts|
     # ...
   end,
   # ...
   'baz' => OptionParser.new do |opts|
     # ...
   end
 }

 global.order!
 subcommands[ARGV.shift].order!

这篇关于使用ruby的OptionParser解析子命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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