OptionParse in Ruby and params not starting with '-'
Asked Answered
O

1

6

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?

Order answered 2/2, 2012 at 18:22 Comment(0)
P
9

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
Postdiluvian answered 2/2, 2012 at 19:38 Comment(3)
This way I cannot be sure if dothis or dothat was the first parameter, right?Acetone
Yes, you are right. You can think of it like script [command] [options]. Wherein command and options are positionally interchangeable. So it could also be script [options] [command]. Does that work for you?Postdiluvian
and what would be a good way of getting possible commands into the usage string? just stick it into the opts.banner?Ostracoderm

© 2022 - 2024 — McMap. All rights reserved.