tags:

views:

786

answers:

1

I need to invoke getoptlong multiple times, but after the first time ARGV is empty.

+4  A: 

Capture the args before the first call, put them back when you're done. Sounds like you're doing something kind of weird, though.

Edit: (expanded)

There's a lot of copying and pasting in here. I consider that helping with clarity:

require 'getoptlong'

storage = ARGV.clone

opts = GetoptLong.new(
  ['--help', '-h', GetoptLong::NO_ARGUMENT ],
  [ '--repeat', '-n', GetoptLong::REQUIRED_ARGUMENT ],
  [ '--name', GetoptLong::OPTIONAL_ARGUMENT ]
)

puts "Before: #{ARGV.inspect}"
opts.each { |opt, arg| puts "Parsed #{opt} = #{arg}" }
puts "After: #{ARGV.inspect}"

# Copy
storage.each {|x| ARGV << x }

opts = GetoptLong.new(
  ['--help', '-h', GetoptLong::NO_ARGUMENT ],
  [ '--repeat', '-n', GetoptLong::REQUIRED_ARGUMENT ],
  [ '--name', GetoptLong::OPTIONAL_ARGUMENT ]
)

puts "Before 2: #{ARGV.inspect}"
opts.each { |opt, arg| puts "Parsed #{opt} = #{arg}" }
puts "After 2: #{ARGV.inspect}"
Dustin
Doesn't quite work. I'm calling getoptlong within a class constructor. I'm subclassing this class (ruby's TestUnit framework) multiple times in one file.Redefining ARGV from within a method generates an error in Ruby
Aaron F.
You don't need to redefine it. I'll expand.
Dustin
Works great, thanks for the clarification!
Aaron F.
Great. I hope your actual code has a bit more reuse than I had here. :)
Dustin