Array of valid arguments in optparse

Hi,

I am trying to use optparse to parse an argument into an array and check
for possible values. For instance consider an argument like this

–operations count, count+, count-

I want to parse above argument into @options[:operations] = [“count”,
“count+”, “count-”]. But at the same time I have limited vocabulary for
possible operations and I want to check for that so that if some gives
any other operation argument, it throws an error message

@OPERATIONS=[“count”, “count+”, “count-”]
@optparse = OptionParser.new do |opts|
opts.banner = “Usage: ruby #{FILE}
–operations=METHOD1,METHOD2,METHOD3…”

          opts.on('-o OPERATIONS', '--operations a,b,c',

@OPERATIONS, Array, “Possible operations are #{@OPERATIONS.join(’, ')}”
) do |hypo|
@options[:operations]=[] unless @options[:operations]
@options[:operations] << hypo.to_s.strip.downcase()
@options[:operations] = @options[:operations].uniq
end
end
@optparse.parse!

Ritesh A. wrote in post #985009:

I am trying to use optparse to parse an argument into an array and check
for possible values. For instance consider an argument like this

–operations count, count+, count-

I want to parse above argument into @options[:operations] = [“count”,
“count+”, “count-”].

Well, the spaces will cause the shell to split it; the user will
probably need to type

–operations count,count+,count-

or

–operations “count, count+, count-”

If you look at the source code for optparse.rb you’ll find an example of
list arguments:

# List of arguments.

opts.on("–list x,y,z", Array, “Example ‘list’ of arguments”)

do |list|

options.list = list

end

But at the same time I have limited vocabulary for
possible operations and I want to check for that so that if some gives
any other operation argument, it throws an error message

Just throw the error yourself.

OPERATIONS = [“count”, “count+”, “count-”]

opts.on … do |hypo|
raise OptionParser::InvalidArgument, “Invalid operation” unless (hypo

  • OPERATIONS).empty?
    end