From: LDC - Jairo Eduardo Lopez Date: 2007-05-25T07:46:46+09:00 Subject: Re: Ruby, OptionParser and multiple flags On Fri, 25 May 2007, ara.t.howard wrote: > > On May 24, 2007, at 10:13 AM, LDC - Jairo Eduardo Lopez wrote: > >> Hello all, >> >> I'm currently writing a small script needed for my lab in which I need to >> parse a few command line arguments in a UNIX like way. >> >> My code goes something like this: >> >> ##### >> #!/usr/bin/ruby -w >> >> require 'optparse' >> require 'ostruct' >> >> opciones = OpenStruct.new >> opts = OptionParser.new do |opts| >> opts.on("-u USER", "--uid USER", "UID del usuario.") do |usr| >> opciones.user = usr >> end >> >> opts.on("-h HOST", "--host HOST", String, "Especifica el servidor. Puede >> ser IP o DNS.") do |h| >> > >> opciones.host = h >> end >> >> opts.on("-p PORT", "--port PORT", Integer, "Especifica el puerto del >> servidor. Debe ser entero.") do |p| >> opciones.port = p >> end >> end >> >> begin >> opts.parse!(ARGV) >> rescue Exception => e >> puts e, opts >> exit! >> end >> >> ##### >> >> When I run the script I run into the problem that if I use various flags, >> and forget to put in the required arguments, some flags are taken as >> arguments. I've read that if I use the coding I've used all three flags, >> the argument should be obligatory. >> >> To better explain, I'll give some examples: >> >> ----- >> ./script.rb -h >> missing argument: -h >> ----- >> Works fine. >> >> ----- >> ./script.rb -p >> missing argument: -p >> ----- >> Works fine. >> >> ----- >> ./script.rb -h -p ----- >> The script accepts -p as the argument for -h, which shouldn't happen as -p >> is actually a flag. >> >> I'm not sure what the problem is so I need help. > > you've told the option parser that -h accepts an argument and you've given it > one. there is no restriction that arguments must not start with a '-' so, in > this case, your code is doing it exactly what you told it to do ;-) > > > -a > -- > we can deny everything, except that we have the possibility of being better. > simply reflect on that. > h.h. the 14th dalai lama > > > > Fair enough. I thought that OptionParser looked out for that sort of thing. Is there anyone who can point me in a direction so that I can try and avoid that sort of confusion between arguments? -- Jairo E. Lopez Laboratorio Docente de Computacion Universidad Simon Bolivar