在Ruby中的OptionParse和不以“-”开头的参数

6
我希望参数像这样:

我希望参数像这样:

program dothis --additional --options

并且:

program dothat --with_this_option=value

我不知道如何做到这一点。我唯一能做的是在参数前面使用--

有什么建议吗?

1个回答

9
使用OptionParser处理位置参数,首先使用OptionParser解析开关,然后从ARGV中获取剩余的位置参数:
# optparse-positional-arguments.rb
require 'optparse'

options = {}
OptionParser.new do |opts|
  opts.banner = "Usage: #{__FILE__} [command] [options]"

  opts.on("-v", "--verbose", "Run verbosely") do |v|
    options[:verbose] = true
  end

  opts.on("--list x,y,z", Array, "Just a list of arguments") do |list|
    options[:list] = list
  end
end.parse!

在执行脚本时:

$ ruby optparse-positional-arguments.rb foobar --verbose --list 1,2,3,4,5

p options
# => {:verbose=>true, :list=>["1", "2", "3", "4", "5"]}

p ARGV
# => ["foobar"]

dothisdothat命令可以放在任何位置。无论如何,options哈希和ARGV保持不变:

 # After options
 $ ruby optparse-positional-arguments.rb --verbose --list 1,2,3,4,5 foobar

 # In between options
 $ ruby optparse-positional-arguments.rb --verbose foobar --list 1,2,3,4,5

这样我就不能确定 dothis 还是 dothat 是第一个参数,对吧? - Szymon Lipiński
是的,你是对的。你可以将它看作 script [command] [options] 的形式。其中命令和选项在位置上是可以互换的。所以也可以是 script [options] [command]。这样行吗? - jcsherin
如何将可能的命令放入使用字符串中,有什么好的方法?只需将其放入opts.banner中即可。 - graywolf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接