Nicolas Charvoz Nicolas Charvoz - 26 days ago 10
Ruby Question

List of arguments in OptParse without separator

I'm currently building a simple program which will read and write file on standard output. I want to launch my program this way :

ruby main.rb -f file1 file2 file3
...

But with optParse I cannot get this to work I must include separator .. I need optParse because I handle multiple options (like verbose, help ...). So if I do this :
ruby main.rb -f file1,file2
... It works

How can I achieve this ?

Thanks !

Answer Source

If you don't have option parameters you pass or if all other parameters are optional, you can just pass the files the old-fashioned way: via ARGV. By default, command line options are separated by spaces, not commas.

If you absolutely need to support the -f option, you could add support for ARGV in addition

require "optparse"

options = {
  :files => []
}
opt_parse = OptionParser.new do |opts|
  opts.banner = "Usage: main.rb file(s) ..."

  opts.on("-f", "--files file1,file2,...", Array, "File(s)") do |f|
    options[:files] += f
  end

  opts.on_tail("-h", "--help", "Show this message") do
    puts opts
    exit
  end

end
opt_parse.parse!

options[:files] += ARGV

if options[:files].length == 0
  abort(opt_parse.help)
end

puts options[:files]

Using this method, you can even mix both styles:

$ main.rb -f -f file1,file2 file3 -f file4 file5
file1
file2
file4
file3
file5

(Note file5 is really being passed via ARGV, but it kinda looks like you are using a space as a separator.)