OptionParse in Ruby and params not starting with '-'

I want to have the following parameters:

program dothis --additional --options 

and

 program dothat --with_this_option=value 

and I canโ€™t figure out how to do this. The only thing I managed to do was to use params with -- .

Any ideas?

+6
source share
1 answer

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 
+8
source

Source: https://habr.com/ru/post/907509/


All Articles