为什么我无法将值写入空白CSV文件?无错误

时间:2014-09-29 20:36:10

标签: ruby csv

我总共有7列,其中6列最初填写在我正在编写的CSV文件中。当我尝试用数据填充第7列时,我一直遇到这个错误:

NoMethodError: You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.<<

为什么我一直遇到这个错误?我应该能够将值写入CSV文件的'nil'/空白区域。以下是我的代码:

#Finds two records in the database
accounts = Account.find(1,2)
spammer_status = []

#Makes a call into the akismet API and populates spammer_status array with
#true or false values if the person is a spammer or not.
accounts.each do |accounts| 
  spammer_status << client.comment_check(accounts.last_seen_ip, nil,
                       :comment_author => accounts.name,
                       :comment_author_email => accounts.email,
                       :comment_author_url => accounts.url,
                       :comment_content => accounts.about)
end

#Changes the values from booleans to strings
spammer_status.map! { |value| value.to_s }

#Populates the initial 6 columns from the database values
CSV.open("/var/local/openhub/current/script/akismet_results.csv","w") do |row|
  row << ["id",
          "name",
          "email",
          "url",
          "description",
          "last seen ip",
          "spammer status"]
  accounts.each do |accounts|
    row << [accounts.id,
            accounts.name,
            accounts.email,
            accounts.url,
            accounts.about,
            accounts.last_seen_ip]
  end
end


#Attempts to populate the 7th column, nil error
CSV.foreach("/var/local/openhub/current/script/akismet_results.csv", headers:true) do |row|
 # binding.pry
  row[6] << spammer_status.shift
end

我在这里做错了什么?错误发生在程序的foreach部分。我想要做的就是一次迭代一行,然后将字符串转换的布尔值添加到正确的列。任何帮助将不胜感激?

2 个答案:

答案 0 :(得分:0)

您正在尝试<<nil个对象。 row[6]是零。我相信您只想为row[6]分配一个值,或者如果您想使用<<,只需将其设为row本身。

CSV.foreach("/var/local/openhub/current/script/akismet_results.csv", headers:true) do |row|
 # binding.pry
  row[6] = spammer_status.shift
  # or you could do row << spammer_status.shift
end

答案 1 :(得分:0)

我最终通过重构我的代码来解决这个问题。我不得不承认上述变化写得不是很好。通过将垃圾邮件状态作为方法提取,然后在编写CSV时创建方法调用,我就能够使功能正常工作。

def is_spam?(account)
  spammer_status = client.comment_check(account.last_seen_ip, nil,
                                      :comment_author => account.name,
                                      :comment_author_email => account.email,
                                      :comment_author_url => account.url,
                                      :comment_content => account.about)
  spammer_status.to_s
end

CSV.foreach("/var/local/openhub/current/script/akismet_results.csv","a", headers: true) do |row|
    row << [account.id,
            account.name,
            account.email,
            account.url,
            account.about,
            account.last_seen_ip,
            is_spam?(account)]
  end