To handle positional parameters with OptionParser, first analyze the switches with OptionParser, and then extract 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!
When 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
can be anywhere. The options
and ARGV
hash remains unchanged:
# 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
source share