TIMBERings
TIMBERings

Reputation: 768

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?

Upvotes: 3

Views: 1480

Answers (2)

Simple Lime
Simple Lime

Reputation: 11090

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"}

Upvotes: 2

Bartosz Pietraszko
Bartosz Pietraszko

Reputation: 1407

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"}

Upvotes: 2

Related Questions