Optparse doesn't seem to return ARGV array. Argument Required Error

291 views Asked by At

This is homework and I do not expect you to give me the complete answer.

I'm trying to parse a command line entry such as:

 ./apacheReport.rb -u testlog.txt 

When I enter this:

./apacheReport.rb -u testlog.txt 

I get:

Argument required

My code is:

require_relative 'CommonLog'
require 'optparse'

# puts ARGV.inspect

optparser = OptionParser.new

optU = false
optI = false
optS = false
optH = false

optparser.banner = "apacheReport.rb [options] filename"

        optparser.parse!
rescue => m
        puts m.message
        puts optparser
        exit
end

if ARGV.length < 1
        puts  "Argument required"
        exit
end

userInputFile = ARGV[0]
userInputFile.to_s
file = CommonLog.new(userInputFile)

It should parse the leftover portion of the command into ARGV[0] then should store it as userInputFile and then create a CommonLog object using the file as the constructor. At that point I call the methods that were specified in the command.

It seems that for some reason my ARGV is not being returned. I'm not sure what the issue is.

2

There are 2 answers

0
the Tin Man On

Ruby's OptionParser is easy to use, but you have to puzzle through the documentation. Here's a little example that'd be useful for your code:

require 'optparse'

options = {}
OptionParser.new do |opt|
  opt.on('-u', '--use_this FILE', 'Use this file') { |o| options[:use_this] = o }
end.parse!

options will contain the flags. In this case, if you pass in -u foo, options[:use_this] will be foo.

Save that and try running it without and with a parameter. Also try running it with just a -h flag.

You can search StackOverflow for more answers where I was dealing with OptionParser.

0
Kathryn On

It's hard to tell what's wrong since you code doesn't seem to be working at the moment. The problem may be that the parse! method removes found options from ARGV. So when you write:

optparser.parse!

It removes your two parameters (-u testlog.txt) and this code always fails:

if ARGV.length < 1
        puts  "Argument required"
        exit
end

Instead of looking at ARGV, you need to set up optparser correctly. Perhaps something like:

optparser = OptionParser.new do |opts|
  opts.banner = "apacheReport.rb [options] filename"
  opts.on("-u", "--u-short-for-this", "Whatever u stands for") do |u|
    optU = u
  end
end

Then optU will be true only if the user passed -u and the filename will be in ARGV[0].