optparse and required arguments

E

E F van de Laar

Hi,

I'm playing around with optparse and ran into something I couldn't get
working right off hand. I define two options; both of which require an
argument. I'm using a rescue clause "catch all" to catch options which
do not get an argument passed in. If I pass two of these on the command
line the second option gets passed as an argument to the first. Anyone
have an idea on how to get around this?

The test script and output...

emiel@marvin:~/co/tally> cat test.rb
require 'optparse'

ARGV.options do |opts|
opts.on("-L=LIB", String) { |arg| puts "-L=" +arg }
opts.on("-R=LIB", String) { |arg| puts "-R=" +arg }
begin
opts.parse!
rescue
$stderr.puts "Error: #{$!}\n\n" + opts.to_s
exit 1
end
end

% ruby1.8 test.rb -L -R quux
-L=-R

% ruby1.8 test.rb -L foo -R
-L=foo

Cheers,

Emiel
 
N

nobu.nokada

Hi,

At Sat, 17 Jan 2004 09:12:14 +0900,
E said:
I'm playing around with optparse and ran into something I couldn't get
working right off hand. I define two options; both of which require an
argument. I'm using a rescue clause "catch all" to catch options which
do not get an argument passed in. If I pass two of these on the command
line the second option gets passed as an argument to the first. Anyone
have an idea on how to get around this?

If you want -L to get an argument only when next string doesn't
seem an option, use "-L [LIB]".
require 'optparse'

ARGV.options do |opts|
opts.on("-L [LIB]", String) { |arg| puts "-L=#{arg.inspect}" }
opts.on("-R [LIB]", String) { |arg| puts "-R=#{arg.inspect}" }
begin
opts.parse!
rescue
$stderr.puts "Error: #{$!}\n\n" + opts.to_s
exit 1
end
end

% ruby1.8 test.rb -L -R quux
-L=nil
-R="quux"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top