tags:

views:

551

answers:

3

I'm trying to use optparse to parse command line arguments. I would like my program to accept arguments like that:

$ ./myscript.rb [options] filename

I can easily manage the [options] part:

require 'optparse'

options = { :verbose => false, :type => :html }

opts = OptionParser.new do |opts|
  opts.on('-v', '--verbose') do
    options[:verbose] = true
  end
  opts.on('-t', '--type', [:html, :css]) do |type|
    options[:type] = type
  end
end
opts.parse!(ARGV)

But how do I get the filename?

I could extract it manually from ARGV, but there has to be a better solution, just can't figure out how

A: 

I don't think extracting it before sending it to OptionParser is bad, I think it makes sense. I probably say this because I have never used OptionParser before, but oh well.

require 'optparse'

file = ARGV.pop
opts = OptionParser.new do |opts|
  # ...
end
August Lilleaas
I can't just use ARGV.pop. For example when the last argument is "css" it could either be a file or belong to --type switch.
Rene Saarsoo
+2  A: 

The "parse" method returns the unprocessed ARGV. So in your example, it will return a one element array with the filename in it.

hallidave
Great, that seems to do the trick. Thanks.
Rene Saarsoo
+1  A: 

I can't just use ARGV.pop. For example when the last argument is "css" it could either be a file or belong to --type switch.

But if your script requires the last argument to be a filename (which is what your usage output inquires) this case should never happen the script should exit with a non-zero and the user should get a usage report or error.

Now if you want to make a default filename or not require a filename as the last argument but leave it optional then you could just test to see if the last argument is a valid file. If so use it as expected otherwise continue without etc.