Help using optionparser

Hi,

I wanted to take cmd line inputs of the form

File.rb -p A
File.rb -p B STRING
File.rb -p C STRING

Im using optionparser to parse the arguments.

I can create an arg and force it to accept inputs of A/B/C but how do i
ensure the extra arg is accepted only when its B/C?

opts.on("-p [STRING]", [:A,:B,:C], "") do |v|
  options[:p] = v
end

···

--
Posted via http://www.ruby-forum.com/.

The non-flag command line arguments are left in ARGV after
OptionParser runs. So you would do something like

if options[:p] == 'B' or options[:p] == 'C'
  if ARGV.length != 0
    raise 'unexpected argument'
  else
    do_stuff ARGV[0]
  end
end

-- Matma Rex

If it is positional, use Array instead of fixed values and check manually:

opts.on "-p [STRING]", Array do |ary|
  raise OptionParser::InvalidArgument, "'A' cannot be followed by other values"
  # …
end

File.rb -p A,String # fails
File.rb -p B,String

If you use this type of input multiple times you can create a validator you can reuse, too

···

On Jun 15, 2012, at 6:11 PM, "cyber c." <lists@ruby-forum.com> wrote:

I wanted to take cmd line inputs of the form

File.rb -p A
File.rb -p B STRING
File.rb -p C STRING

Im using optionparser to parse the arguments.

I can create an arg and force it to accept inputs of A/B/C but how do i ensure the extra arg is accepted only when its B/C?

opts.on("-p [STRING]", [:A,:B,:C], "") do |v|
options[:p] = v
end

Thank you all for the suggestions :slight_smile:

···

--
Posted via http://www.ruby-forum.com/.

Yes. Note that one has to use OptionParser#parse! in order to have it
remove options from the command line. I usually do

OptionParser.new do |opts|
  opts.on ...
end.parse! ARGV

Kind regards

robert

···

On Sat, Jun 16, 2012 at 11:32 AM, Bartosz Dziewoński <matma.rex@gmail.com> wrote:

The non-flag command line arguments are left in ARGV after
OptionParser runs. So you would do something like

if options[:p] == 'B' or options[:p] == 'C'
if ARGV.length != 0
raise 'unexpected argument'
else
do_stuff ARGV[0]
end
end

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/