aris
1
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
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 R.
On Jun 15, 2012, at 6:11 PM, “cyber c.” [email protected] wrote:
opts.on(“-p [STRING]”, [:A,:B,:C], “”) do |v|
options[:p] = v
end
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 Sat, Jun 16, 2012 at 11:32 AM, Bartosz Dziewoński
[email protected] 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
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
Thank you all for the suggestions 