insecure-IT
insecure-IT

Reputation: 2188

How do you use OptionParser to open a file with command-line options?

I'm getting this error when trying to print line from a file via command-line options

no implicit conversion of true into String (TypeError)
from threat_detection.rb:64:in 'new'
from threat_detection.rb:64:in '<main>'

If I use the file name instead of options[:config_file] it prints the lines of the file, as expected.

if options[:config_file]
  File.new(options[:config_file], 'r').each { |params| puts params }
end

if options[:host_file]
  File.new(options[:host_file], 'r').each { |host| puts host }
end

Upvotes: 2

Views: 580

Answers (1)

user3373470
user3373470

Reputation:

Looks like you are trying to use the OptionParser class in Ruby. Since it is not a part of the core library, make make sure to include the following at the top of your program:

require 'optparse'

Furthermore, make sure you are creating your options correctly:

options = {}

optparse = OptionParser.new do |opts|
  options[:config_file] = nil
  opts.on('-f', '--config-file', 'Enter the config file to open.') do
    options[:dry_run] = true
  end
end

optparse.parse!

When using a flag in command line, you are essentially setting a variable to true or false. For example, by default, -v (verbose) is set to false for most operations (like rm). Following the command and its optional flags are (sometimes required) command-line arguments, which is the filename in your case.

Calling your script should look similar to

$ ruby ./my_program.rb --config-file /path/to/some/file
       ^               ^             ^
       program         flag          argument

As you saw, an optparse option must be a boolean. You only want to open a file if the flag is present (option is true). Just a slight change is needed for your program to run:

if options[:config_file]
  File.new(ARGV[0], 'r').each { |params| puts params }
end

ARGV is an array of all command-line arguments to your script (following flags). If you only include one argument, you will want the first element, or index 0 (ARGV[0]). All arguments are separated by spaces. So if you implement the same technique for options[:host_file], you can use ARGV[1].

Upvotes: 1

Related Questions