I'm trying to learn how to use optparse to take in command line options however I am having a hard time getting it to function as it shows in the class documentation and any examples I can find online. Specifically when I pass the -h option nothing is coming up. I can output ARGV and its showing that it receives -h but it wont display opts.banner and or any of the opts. What am I missing here?
class TestThing
def self.parse(args)
options = {}
options[:time] = 0
options[:operation] = :add
options[:input_file] = ARGV[-2]
options[:output_file] = ARGV[-1]
optparse = OptionParser.new do |opts|
opts.banner = "Usage:[OPTIONS] input_file output_file"
opts.separator = ""
opts.separator = "Specific Options:"
opts.on('-o', '--operation [OPERATION]', "Add or Subtract time, use 'add' or 'sub'") do |operation|
optopns[:operation] = operation.to_sym
end
opts.on('-t', '--time [TIME]', "Time to be shifted, in milliseconds") do |time|
options[:time] = time
end
opts.on_tail("-h", "--help", "Display help screen") do
puts opts
exit
end
opt_parser.parse!(args)
options
end
end
end
You need to hold onto the results of OptionParser.new
and then call parse!
on it:
op = OptionParser.new do
# what you have now
end
op.parse!
Note that you'll need to do this outside the block you give to new
, like so:
class TestThing
def self.parse(args)
options = {}
options[:time] = 0
options[:operation] = :add
options[:input_file] = ARGV[-2]
options[:output_file] = ARGV[-1]
optparse = OptionParser.new do |opts|
opts.banner = "Usage:[OPTIONS] input_file output_file"
# all the rest of your app
end
optparse.parse!(args)
end
end
(I left your indentation in to make it clearer what I mean, but on a side note, you'll find the code easier to work with if you indent consistently).
Also, you don't need to add -h
and --help
- OptionParser
provides those for you automatically and does exactly what you've implemented them to do.