tags:

views:

209

answers:

3

I need to parse a command line like

  script.rb <mandatory filename> [options]

with optparse.

Sure I can write some custom code to handle the filename, then pass ARGV to optparse, but maybe there's a simpler way to do it?

EDIT: there's another hacky way to parse such a command line, and that is pass ['--mandatory-filename'] + ARGV to optparse, then handle the --mandatory-filename option.

+1  A: 

First parse with optparse, then scan the ARGV and raise if ARGV is empty/unusable/not provided. The mandatory filename will not be processed by optparse and will be left for you in ARGV - if it's not there, just raise manually.

Julik
A: 

Optparse only does arguments with parameters, AFAIK. The "correct" way to handle your filename is to deal with it outside of optparse. I posted some example code for this in answer to this question.

BTW, that's a rather unusual commandline. If it's just for you, fine, but others are likely to find it rather counter-intuitive. It would be more normal to have: script.rb [options] <filename>...

Shadowfirebird
Thanks, point taken
Leonid Shevtsov
A: 

Just to follow up on what Julik and Shadowfirebird said: When parsing with OptionParser be aware that #parse! and #parse have different functionality. The former will remove every argument it understands out of the passed array where the latter will leave them be. This changes your conditions for determining if the required argument is present.

Geoff