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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With