When I run this sample from the OptionParser documentation:
require 'optparse'
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: example.rb [options]"
opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
options[:verbose] = v
end
end.parse!
p options
p ARGV
and type: ruby test.rb -v 100
, it returns:
{:verbose=>true}
["100"]
Shouldn't verbose be 100
, not a boolean?
I have no idea about this, does anyone have any advice?
The choices option attribute (a sequence of strings) defines the set of allowed option arguments. optparse.check_choice () compares user-supplied option arguments against this master list and raises OptionValueError if an invalid string is given. The whole point of creating and populating an OptionParser is to call its parse_args () method:
Returns the Option instance with the option string opt_str, or None if no options have that option string. Return True if the OptionParser has an option with option string opt_str (e.g., -q or --verbose ). If the OptionParser has an option corresponding to opt_str, that option is removed.
Return True if the OptionParser has an option with option string opt_str (e.g., -q or --verbose ). If the OptionParser has an option corresponding to opt_str, that option is removed. If that option provided any other option strings, all of those option strings become invalid.
If the OptionParser has an option corresponding to opt_str, that option is removed. If that option provided any other option strings, all of those option strings become invalid. If opt_str does not occur in any option belonging to this OptionParser, raises ValueError.
You've specified that the -v
option does not have an argument:
opts.on("-v", ...
If you want it to take an argument then you have to say so:
opts.on("-v n", "--verbose=n", ...
#-----------^
And if you want to force n
to be an integer, then:
opts.on('-v n', '--verbose=n', OptionParser::DecimalInteger, ...
You want to start reading at the make_switch
docs (such as it is) and then reverse engineer the examples.
Don't feel bad about being confused, the OptionParser documentation isn't quite the best thing ever.
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