Nathan Campos
Nathan Campos

Reputation: 29497

Option With 2 Arguments in OptParse

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?

Upvotes: 2

Views: 412

Answers (2)

KITAITI Makoto
KITAITI Makoto

Reputation: 116

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")

Upvotes: 3

vladr
vladr

Reputation: 66661

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

Upvotes: 5

Related Questions