Question

I'm trying to do something that looks like this:

opt_parser = OptionParser.new do |opt|
    opt.banner = "Test"
    opt.separator ""
    opt.on("-t", "--test arg1 arg2", "Test") do |arg1, arg2|
        puts arg1
        puts arg2
    end
end

The problem is that it returns the arg1, but arg2 returns nil. How to make this work?

Was it helpful?

Solution

The accepted way of specifying a list of values for a given option is by repeating that option (for example the -D option as accepted by java and C compilers), e.g.

my_script.rb --test=arg1 --test=arg2

In some cases, the nature of your arguments may be such that you can afford to use a separator without introducing ambiguity (for example the -classpath option to java or, more clearly, the -o option to ps), so if arg1 and arg2 can never normally contain a comma , then you could also accept e.g.

my_script.rb --test=arg1,arg2

The code that supports both conventions above would be something along the lines of:

require 'optparse'
...
test_vals = []
...
opt_parser = OptionParser.new do |opt|
    ...
    opt.on("-t", "--test=arg1[,...]", "Test") do |arg|
        test_vals += arg.split(',')
    end
    ...
end

opt_parser.parse!

puts test_vals.join("\n")

Then:

$ my_script.rb --test=arg1 --test=arg2
arg1
arg2

$ my_script.rb --test=arg1,arg2
arg1
arg2

$ my_script.rb --test=arg1 --test=arg2,arg3
arg1
arg2
arg3

OTHER TIPS

If vladr's answer is acceptable, alternate way is to pass Array as third argument to #on:

require 'optparse'

test_vals = []

opt_parser = OptionParser.new do |opt|
  opt.banner = "Test"
  opt.separator ""
  opt.on("-t", "--test arg1[,...]", Array, "Test") do |args|
    test_vals += args
  end
end

opt_parser.parse!

puts test_vals.join("\n")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top