array of valid arguments in optparse

R

Ritesh Agrawal

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[:eek:perations] = ["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[:eek:perations]=[] unless @options[:eek:perations]
@options[:eek:perations] << hypo.to_s.strip.downcase()
@options[:eek:perations] = @options[:eek:perations].uniq
end
end
@optparse.parse!
 
B

Brian Candler

Ritesh Agrawal 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[:eek:perations] = ["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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,150
Members
46,697
Latest member
AugustNabo

Latest Threads

Top