From: Joel VanderWerf Date: 2006-11-14T11:09:34+09:00 Subject: Re: parsing unknown options Paul Lutus wrote: > Stefano Crocco wrote: ... >> The problem is that, as far as I can tell, OptParse will raise an >> exception when it finds an unknown option (i.e as soon as it hits -c in >> my example above). Is there a way around this behavior? Or does anybody >> know of a better way to approach the whole problem? > > Sure. Parse the command line yourself. I don't recommend it unless your syntax is simple or you like writing command line parsers. It just so happens that yesterday I wrote a command line parser that may help in this case. I wrote it because getopt/long wasn't deleting option arguments from ARGV, so it was hard to use with ARGF. My parser leaves any unknown options it finds in ARGV. It has some other nice features[1] and only a few limitations[2]. Basically, it does one thing: turn an array of strings into a hash of recognized options and their arguments, leaving unrecognized strings in the original array. I didn't plan on releasing this today, but there's really no reason not to. It's called argos[3]. For now it lives at: http://redshift.sourceforge.net/argos.rb The heart of it is simple enough (about 40 lines) to copy and paste into a small ruby program file, if you don't want to require it as a library. Here's a simple example: require 'argos' optdef = { "v" => true, "n" => proc {|arg| Integer(arg)} } argv = %w{-v -n10 filename} opts = Argos.parse_options(argv, optdef) p opts # ==> {"v"=>true, "n"=>10} p argv # ==> ["filename"] [1] Features: Output is a hash of {option => value, ...}. Supports both long ("--foo") and short ("-f") options. A long option with an argument is --foo=bar or --foo bar. A short option with an argument is -fbar or -f bar. The options -x and --x are synonymous. Short options with no args can be combined as -xyz in place of -x -y -z. The string "--" terminates option parsing, leaving the rest untouched. [2] Limitations: A particular option takes either 0 args or 1 arg. There are no optional arguments, in the sense of both "-x" and "-x3" being accepted. Options lose their ordering in the output hash (but they are parsed in order and you can keep track using state in the handler closures). There is no usage/help output. [3] Argos was Odysseus' faithful dog, who was good at recognizing ;) -- vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407