NoMethodError:未定义的方法“ map”为true:TrueClass用于映射标头/创建CSV

时间:2019-07-02 14:58:18

标签: ruby-on-rails ruby selenium-webdriver pry

我正在下载一堆CSV,以便将它们转储为一个大CSV以便导出。我正在使用Selenium / Ruby / Ruby-on-rails(?)来实现此目的。

我目前遇到的问题是我得到

NoMethodError: undefined method `map' for true:TrueClass Did you mean? tap

对于以下代码:

def csv_creation(source)

      l_source = {'lead_source' => source.to_s}

      input_file = Dir.glob("path_to_file/name_of_files*.csv").last

      rows = CSV.open(input_file, headers: true).map(&:to_h)

      rows.each { |h| h.merge!(l_source) }

      headers = rows.first.keys

      rows.first.keys.each { |k| puts k }

      csv_response = CSV.generate do |csv|
        csv << headers

        rows.each do |row|
          csv << row.values_at(*headers)
        end
      end

      File.open("#{source}.csv", "w") { |file| file.write(csv_response) }

      input_files = Dir.glob("#{source}*.csv")

      all_headers = input_files.reduce([]) do |all_header, file|
        header_line = File.open(file, &:gets)

        all_headers | CSV.parse_line(header_line)
      end

      CSV.open("out.csv", "a+") do |out|
        out << all_headers

        input_files.each do |file|
          CSV.foreach(file, headers: true) do |row|

            out << all_headers.map{ |header| row[header] }

          end
        end
      end
    end

在被告知我必须在rails c上运行它并放入一个模块之前,这段代码起作用了。我没有Ruby或RoR的经验,但显然,这种转变扰乱了我的代码。

随机花絮:

  • “源”保存从下拉菜单中收集的文本

  • 有问题的模块是由我的托管公司构建的,因此我不确定它包含的模块-抱歉。

  • Rails c并没有真正给出发生此错误的行号,但是我认为它是在第二个“ map”中发生的,因此我打印出了一些行以查看是否有任何异常但没有任何异常是。它从某个地方获得了“真实”的价值,老实说我不知道​​在哪里。一切都应该是一个字符串。

一些见识将不胜感激。

1 个答案:

答案 0 :(得分:1)

我想我现在看到了错误:正如我评论的那样,

      all_headers = input_files.reduce([]) do |all_header, file|
         header_line = File.open(file, &:gets)
         all_headers | CSV.parse_line(header_line)
     end

是无意义的:请注意,在第一次执行do ...结束块时,all_headers为nil,因为该变量已定义但未分配。当您计算all_headers | CSV.parse_line(header_line)时,它等效于nil | [ ... something ...],并且计算结果为true。每次重复都会重复一次,最后,all_headers收到值true

我认为您的意思是all_header | CSV.parse_line(header_line)