rubyoptparse

Extracting filenames from command line arguments with Ruby


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


Solution

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