Bryan Richardson wrote:
Perfect!!! Thanks for the help.
I see several problems with that solution:
1) It uses an undocumented feature: the .options attribute of ARGV.
2) It uses the try/except mechanism which slows down your program when a
exception actually occurs.
3) The fact that an option might not be a wrapper option is not an
exceptional event--you regularly expect that to be the case.
4) It requires that you use a user defined array in place of ARGV.
Here's another solution:
require 'optparse'
p ARGV
puts
opts = OptionParser.new do |opts|
#wrapper option where value is required:
opts.on("-t=RANDOM_CHARS") do |val|
puts "-t option entered with value=#{val}"
opt_index = ARGV.index('-t')
#delete option and its value:
ARGV.delete_at(opt_index) #rest of elements move one spot to the
left
ARGV.delete_at(opt_index)
end
#wrapper option where value is optional:
opts.on("-y [=RANDOM_CHARS]") do |val| #val==nil if no value for
option
puts "-y option entered with value=#{val}"
opt_index = ARGV.index('-y')
ARGV.delete_at(opt_index)
if val
ARGV.delete_at(opt_index)
end
end
#non-wrapper option:
opts.on("-a=RANDOM_CHARS") do |val|
puts "-a option entered with value=#{val}"
end
end
opts.parse(ARGV)
p ARGV
Problems with that solution:
I'm not thrilled with the code that deletes elements out of ARGV--that's
inefficient because the rest of the elements have to be shuffled over
one spot. On the other hand, if I collect all the desired options into
an array and then assign the array to ARGV, I get a warning:
warning: already initialized constant ARGV
···
--
Posted via http://www.ruby-forum.com/\.