Search code examples
rubyoptparse

OptionParse in Ruby and params not starting with '-'


I want to have params like this:

program dothis --additional --options

and:

program dothat --with_this_option=value

and I can't get how to do that. The only thing I managed to do is to use params with -- at the beginning.

Any ideas?


Solution

  • To handle positional parameters using OptionParser, first parse the switches using OptionParser and then fetch the remaining positional arguments from ARGV:

    # optparse-positional-arguments.rb
    require 'optparse'
    
    options = {}
    OptionParser.new do |opts|
      opts.banner = "Usage: #{__FILE__} [command] [options]"
    
      opts.on("-v", "--verbose", "Run verbosely") do |v|
        options[:verbose] = true
      end
    
      opts.on("--list x,y,z", Array, "Just a list of arguments") do |list|
        options[:list] = list
      end
    end.parse!
    

    On executing the script:

    $ ruby optparse-positional-arguments.rb foobar --verbose --list 1,2,3,4,5
    
    p options
    # => {:verbose=>true, :list=>["1", "2", "3", "4", "5"]}
    
    p ARGV
    # => ["foobar"]
    

    The dothis or dothat commands can be anywhere. The options hash and ARGV remains the same regardless:

     # After options
     $ ruby optparse-positional-arguments.rb --verbose --list 1,2,3,4,5 foobar
    
     # In between options
     $ ruby optparse-positional-arguments.rb --verbose foobar --list 1,2,3,4,5