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?
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
script [command] [options]
. Wherein command and options are positionally interchangeable. So it could also be script [options] [command]
. Does that work for you? –
Postdiluvian opts.banner
? –
Ostracoderm © 2022 - 2024 — McMap. All rights reserved.
dothis
ordothat
was the first parameter, right? – Acetone