Ruby OptionParser not parsing -- commands properly

1.3k Views Asked by At

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?

2

There are 2 best solutions below

0
Simple Lime On BEST ANSWER

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"}
0
Bartosz Pietraszko On

It might not work because .parse method should receive an array of arguments as a parameter - not a string. Once you put your OptionParser in an actual script and .parse(ARGV), both --format s and --format==s variants of long style switch should work.

opt.rb script:

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

Usage:

~ ruby opt.rb -f s  
{"format"=>"s"}
~ ruby opt.rb --format s
{"format"=>"s"}
~ ruby opt.rb --format=s
{"format"=>"s"}