从csv文件创建哈希给出错误

时间:2014-03-12 12:00:18

标签: ruby-on-rails ruby ruby-on-rails-3 csv

我想从一个包含大量数据的CSV文件中创建一个哈希值 我的ruby文件代码看起来像

hersteller = Hash[CSV.read("db/red.csv", col_sep: ',', row_sep: :auto, headers: true).map {|row| [row["lieferant_nr"], row["beschreibung"]]}] #this is line number 45

 CSV.foreach("db/red.csv", col_sep: ',', row_sep: :auto, headers: true) do |row|  # map keys

  hash = Hash[row.map {|k, v| mapping[k] ? [mapping[k], v && v.strip.gsub("\u00A0", "")] : nil}.compact]  # ignore NULL values

  hash.reject! {|k, v| v == "NULL"}  # get hersteller names

  hash["hersteller"] = hersteller[hash["hersteller_nummer"]].strip.gsub("\u00A0", "") if hash["hersteller_nummer"].present? #this is line number 54

当我创建哈希

时,这给了我一个错误
  
    

未定义的方法strip' for nil:NilClass /home/anish/helios/dynalink/db/seeds.rb:54:in阻止在顶部(必填)>'     /home/anish/helios/dynalink/db/seeds.rb:46:in top(required)>'

  

有谁能告诉我这里出了什么问题.... 提前致谢

1 个答案:

答案 0 :(得分:0)

变化:

hash["hersteller"] = hersteller[hash["hersteller_nummer"]].strip.gsub("\u00A0", "") if hash["hersteller_nummer"].present? #this is line number 54

为:

hash["hersteller"] = hersteller[hash["hersteller_nummer"]].strip.gsub("\u00A0", "") if hersteller[hash["hersteller_nummer"]].present?

您应检查是否存在hersteller[hash["hersteller_nummer"]]而不是hash["hersteller_nummer"]