3

这是 OptionParser 的精简版

    OptionParser.new do |opts|
      opts.on('-f', '--format FORMAT', 'output format (text, html, yml, json, xml)') do |format|
        options['format'] = format
      end
    end

这是格式选项的试用版

[16] pry(main)> parse("-f s")
=> {"format"=>" s"}
[17] pry(main)> parse("--format s")
OptionParser::InvalidOption: invalid option: --format s

为什么不起作用--format s

4

2 回答 2

2

它可能不起作用,因为.parse方法应该接收参数数组作为参数 - 而不是字符串。一旦你把你OptionParser放入一个实际的脚本中,长样式开关的.parse(ARGV)两个--format s和变体都应该可以工作。--format==s

opt.rb 脚本:

require 'optparse' 

options = {}
parser = OptionParser.new do |opts|
  opts.on('-f', '--format FORMAT', 'output format (text, html, yml, json, xml)') do |format|
    options['format'] = format
  end 
end
parser.parse(ARGV)
p options

用法:

~ ruby opt.rb -f s  
{"format"=>"s"}
~ ruby opt.rb --format s
{"format"=>"s"}
~ ruby opt.rb --format=s
{"format"=>"s"}
于 2018-07-19T19:48:09.600 回答
2

手动调用的时候parse需要传入 ,ARGV不是脚本名后面所有内容的字符串,而是拆分后的数组:

./example.rb -f s       # => ["-f", "s"]
./example.rb --format s # => ["--format", "s"]
./example.rb --format=s # => ["--format=s"]

因此,如果我们将这些格式传递给解析,我们会得到正确解析的选项:

op.parse(['-f', 'a'])       # => {"format"=>"a"}
op.parse(['--format', 'b']) # => {"format"=>"b"}
op.parse(['--format=c'])    # => {"format"=>"c"}
于 2018-07-19T19:49:30.090 回答