Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OptionParser returning bool instead of argument?

Tags:

ruby

optparse

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?

like image 729
CrazyLion Avatar asked Mar 06 '12 03:03

CrazyLion


People also ask

How do I parse option arguments in an optionparser?

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:

How do I return an option from an option parser?

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.

How do I know if an optionparser option string is invalid?

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.

What happens if OPT_STR does not occur in optionparser?

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.


1 Answers

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.

like image 77
mu is too short Avatar answered Oct 10 '22 21:10

mu is too short