How do I handle a missing mandatory argument in Ruby OptionParser?

Posted by Rob Jones on Stack Overflow See other posts from Stack Overflow or by Rob Jones
Published on 2010-03-30T17:23:44Z Indexed on 2010/03/30 20:03 UTC
Read the original article Hit count: 372

Filed under:
|
|

In OptionParser I can make an option mandatory, but if I leave out that value it will take the name of any following option as the value, screwing up the rest of the command line parsing. Here is a test case that echoes the values of the options:

$ ./test_case.rb --input foo --output bar
output  bar
input  foo

Now leave out the value for the first option:

$ ./test_case.rb --input  --output bar
input  --output

Is there some way to prevent it taking another option name as a value? Thanks!

Here is the test case code:

#!/usr/bin/env ruby
require 'optparse'
files = Hash.new

option_parser = OptionParser.new do |opts|
  opts.on('-i', '--input FILENAME', 'Input filename - required') do |filename|
    files[:input] = filename
  end
  opts.on('-o', '--output FILENAME', 'Output filename - required') do |filename|
    files[:output] = filename
  end
end

begin
  option_parser.parse!(ARGV)
rescue OptionParser::ParseError
  $stderr.print "Error: " + $! + "\n"
  exit
end

files.keys.each do |key|
  print "#{key}  #{files[key]}\n"
end

© Stack Overflow or respective owner

Related posts about ruby

Related posts about optionparser