On Tue, 15 Mar 2005, Jos Backus wrote:

> OptionParser is still a mystery to me. In the example below, how do I
> distinguish between a -c flag without an argument (which is a fatal syntax
> error) and no -c flag at all? In both cases client equals nil. There doesn't
> seem to be a way to intercept the `missing argument' message, or if there is,
> I can't seem to find it in the documentation :-/
> 
>     require 'optparse'
> 
>     client = nil
>     ARGV.options do |opt|
>       opt.on("-c CLIENT", String) do |s|
> 	puts "client: #{s}"
> 	client = s
>       end
>       opt.parse!
>     end
> 
>     puts "client is #{client}" if client
> 
>     puts "done"
> 
> Running the example yields:
> 
>     lizzy:~% ruby op -c foo
>     client: foo
>     client is foo
>     done
>     lizzy:~% ruby op -c    
>     op: missing argument: -c
>     done
>     lizzy:~% ruby op   
>     done
>     lizzy:~% 

Try [CLIENT] instead of CLIENT:

require 'optparse'

client = nil
ARGV.options do |opt|
  opt.on("-c [CLIENT]", String) do |s|
    puts "client: #{s}"
    client = s
  end
  opt.parse!
end

puts "client is #{client}" if client

puts "done"

 

-- 
Wybo