SuperManEver
SuperManEver

Reputation: 2362

How to get command line argument using optparse?

I'm working on command line search tool which searches through source files using given keyword. I use optparse to parse command line options. For now it look like this:

qs -p ~/Desktop/project -k line

if no -p argument is provided I use default(current) directory:

qs -k line

But, what I really want is doing the same as above but without -k, like this:

qs line

For now I have this:

OptionParser.new do |options|

  options.banner = "Usage: qs [options] [path] [keyword]\n" \
                   "\nSearch through files for a given keyword at specified path.\n" \
                   "If path is no specified current directory used by default."

  options.separator ""
  options.separator "Specific options:"

  options.on("--no-rec", "Looking in files only at that level.") do |r|
    $values[:recursion] = r
  end

  options.on('-p', '--path PATH', String, 'Path where to start search') do |path|
    $values[:path] = path
  end

  options.on('-k', '--key WORD', String, 'Word you are looking for ') do |key|
    $values[:keyword] = key
  end    

  options.on_tail("-h" , "--help", "Help documentation.") do
    $stderr.puts options
    exit 1
  end
end.parse!

As you can see it's impossible to do something like this:

$values[:keyword] = ARGV[2]

because there is no guarantee that all arguments will be present.

Is it possible to do this, without losing all this support from optparse ?

Thanks in advance.

Upvotes: 0

Views: 196

Answers (1)

matt
matt

Reputation: 79733

When you use parse! (with the !), Optparse removes the options from ARGV, so afterward any other items (that Optparse doesn’t recognise) will be at ARGV[0] onwards.

So you should be able to do something like this:

OptionParser.new do |options|
  # as before, but without k option
end.parse!

# At this point all the options optparse knows about will be
# removed from ARGV, so you can get at what's left:
$values[:keyword] = ARGV[0]

Upvotes: 1

Related Questions