2

尝试通过命令行选项从文件中打印行时出现此错误

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

如果我使用文件名而不是options[:config_file]它会按预期打印文件的行。

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
4

1 回答 1

1

看起来您正在尝试OptionParser在 Ruby 中使用该类。由于它不是核心库的一部分,因此请确保在程序顶部包含以下内容:

require 'optparse'

此外,请确保您正确创建选项:

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!

在命令行中使用标志时,您实际上是将变量设置为trueor false。例如,对于大多数操作(如),默认情况下-v(详细)设置为。在命令及其可选标志之后是(有时是必需的)命令行参数,在您的情况下是文件名。falserm

调用你的脚本应该类似于

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

如您所见, optparse 选项必须是布尔值。如果标志存在(选项为真),您只想打开文件。您的程序只需稍作改动即可运行:

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

ARGV是脚本的所有命令行参数的数组(跟随标志)。如果只包含一个参数,则需要第一个元素,即索引 0 ( ARGV[0])。所有参数都用空格分隔。因此,如果您实现相同的技术options[:host_file],您可以使用ARGV[1].

于 2015-10-16T20:48:14.007 回答