rubyoptionparser

Ruby OptionParser not parsing -- commands properly


Here is a stripped down version of OptionParser

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

Here is the trial for format options

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

Why doesn't --format s work?


Solution

  • When you call parse manually, you need to pass in the ARGV, which is not the string of everything after the script name, but the split array:

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

    So, if we pass those formats to parse we get the options correctly parsed:

    op.parse(['-f', 'a'])       # => {"format"=>"a"}
    op.parse(['--format', 'b']) # => {"format"=>"b"}
    op.parse(['--format=c'])    # => {"format"=>"c"}