Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse an argument without a name with Ruby's optparse

Tags:

ruby

optparse

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.

like image 573
Leonid Shevtsov Avatar asked Mar 15 '10 17:03

Leonid Shevtsov


1 Answers

First parse! with optparse, then scan the ARGV and raise if ARGV is empty. Like so:

op.parse! filename = ARGV.pop raise "Need to specify a file to process" unless filename 

The mandatory filename will not be processed by the OptionParser and will be left for you in ARGV - if it's not there, just raise manually.

like image 96
Julik Avatar answered Sep 28 '22 09:09

Julik