Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 803
TIMBERings Avatar asked Mar 09 '26 16:03

TIMBERings


2 Answers

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"}
like image 122
Simple Lime Avatar answered Mar 12 '26 06:03

Simple Lime


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"}
like image 28
Bartosz Pietraszko Avatar answered Mar 12 '26 05:03

Bartosz Pietraszko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!