Search code examples
rubycommand-line-argumentsoptparse

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?


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