Search code examples
rubyoptparse

Reading a file that is passed as argument while using optparse


I'm writing a program that requires arguments in order to be run, one of those possible arguments is the option to use a file by passing the program -f <file>. I'm not understanding where this is going wrong, I'm attempting to read the file as ARGV[1] because it's the second argument given to the program.

However, calling ARGV[1] outputs nothing, however if I added two more arguments on top of the flag and file name given, and then call on ARGV[1] it will output the last argument given as 1? So for example:

ruby testparse.rb -f test.txt
#<= Nothing there

But if I did this:

ruby testparse.rb -f test.txt test ttest
#<= ttest

That puts ARGV[1] at the location of ARGV[3]? So my questions being:

  • Why can't I call onto a file as ARGV[1] while passing it through optparse?
  • How do I call on the file to be read while using optparse?

Source:

require 'optparse'

options = {}
OptionParser.new do |opt|
  opt.on('-f=FILE', '--file=FILE', 'File it') { |o| options[:file] = o }
end.parse!

if ARGV[1].nil?
  puts "Nothing there"
else
  puts ARGV[1]
end

Solution

  • When you call parse! to parse your command line options, OptionParser removes any that it recognises from ARGV, leaving any it doesn’t recognise for you to handle as you want.

    In your case, since you’ve specified the -f option to take one parameter, those two entries are removed from ARGV. In your code you store the option in options[:file], so check that instead of ARGV[1].