Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OptionParse in Ruby and params not starting with '-'

Tags:

ruby

optparse

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?

like image 352
Szymon Lipiński Avatar asked Feb 02 '12 18:02

Szymon Lipiński


1 Answers

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
like image 105
jcsherin Avatar answered Sep 19 '22 04:09

jcsherin