模块中的Ruby模块和跟踪器变量

时间:2014-03-12 18:16:53

标签: ruby module

我的模块:

module Httpserver
    failures = []
    passes = []

    def self.validate(type, file)
        File.open('01httpserver.txt', 'a') do |out|
            if type == "asa"
                if File.readlines(file).grep(/http server enabled/).any?
                     #failures =+ file
                     out.puts "FAILED: #{file} does have http enabled"
                else
                     #passes =+ file
                     out.puts "PASSED: #{file} does not have http enabled"
                end
            elsif type == "ios"
                if File.readlines(file).grep(/no ip http server/).any?
                    #failures =+ file
                    out.puts "FAILED: #{file} does have http enabled"
                else
                    #passes =+ file
                    out.puts "PASSED: #{file} does not have http enabled"
                end
            end
        end
    end

    def self.close
        File.open('01httpserver.txt', 'a') do |out|
            out.puts "\n"
            failures.each do |failure|
                out.puts failure
            end
        end
    end
end

我的主要脚本调用模块:

asa_files.each do |file|
    Httpserver.validate("asa", file)
    Httpserver.close()
end

现在我想跟踪所有失败,如果我取消注释“failures = = file”行或“pass = + file”行。我收到以下错误。

01httpserver.rb:12:in `block in validate': undefined method `+@' for "bucket/config.txt":String (NoMethodError)
from /Users/****/modules/01httpserver.rb:6:in `open'
from /Users/****/modules/01httpserver.rb:6:in `validate'
from cis.rb:40:in `block in <main>'
from cis.rb:39:in `each'
from cis.rb:39:in `<main>'

这不是跟踪此模块中正在检查的项目失败的正确方法吗?我应该在主脚本中有一个数组并添加到该数组吗?如果这没有意义,请告诉我。

2 个答案:

答案 0 :(得分:1)

Ruby将=+解释为一个赋值后跟一个+运算符,该运算符未在String上定义。您可能正在寻找+=

编辑,抱歉,我误解了错误消息。如Alex建议的那样使用<<push

答案 1 :(得分:0)

您正在尝试使用failures =+ file。正确的运算符为+=,而不是=+

向元素添加元素的正确方法是failures.push(file)