Ruby 检查CSV标头是否存在

Ruby 检查CSV标头是否存在,ruby,csv,Ruby,Csv,我有Rails应用程序的类导入器,在其中我使用方法导入CSV文件 def import CSV.foreach(file.path, headers: true, encoding: "iso-8859-1") do |row| mail = row["email"]||row["Email"]||row["e-mail"]||row["E-mail"]||row["mail"]||row["Mail"] end end 我将变量mail设置为在循环内执行操作,我试图保护它不受

我有Rails应用程序的类导入器,在其中我使用方法导入CSV文件

def import
  CSV.foreach(file.path, headers: true, encoding: "iso-8859-1") do |row|
    mail = row["email"]||row["Email"]||row["e-mail"]||row["E-mail"]||row["mail"]||row["Mail"]
  end
end
我将变量
mail
设置为在循环内执行操作,我试图保护它不受不同名称的邮件列的影响,但我不知道如何打破循环并保持代码干燥,以防出现CSV,而没有任何定义标题的列

编辑:


问题的解决方案

这应该可以让您开始。您需要更改regexp以匹配所有案例

def import
  CSV.foreach(file.path, headers: true, encoding: "iso-8859-1") do |row|
    if row.headers.none?{|e| e =~ /email/i}
      raise "freak out"
    end
  end
end

<>我也会考虑设置一个变量<代码> HasyMeAiLeHealths,因为你不需要扫描每一行的头,因为它们都是相同的。p> Once还可以尝试使用
标题转换器:[:downcase,:symbol]
选项,只需检查较少的值(即不区分大小写),例如
[:email,:mail]

CSV.foreach(file.path, headers: true, header_converters: [:downcase, :symbol], encoding: "iso-8859-1") do |row|
  puts 'You are missing the "email" header!' unless [:email, :mail].all? { |header| row.headers.include? header }
  # refine/refactor as necessary...
  # do rest of function...
end
有关的文档。

根据,您还可以使用
返回\u标题:true
在稍后的循环中检查
标题行?
。下面是一个例子:

data = CSV.read("your.csv", headers: true, return_headers: true)
(0..(data.length-1)).each do |row|
   if  data[row].header_row? then
      p "yes header!"
   end
end

失败“输入数据中没有电子邮件”,除非邮件
正常,但当单个记录没有电子邮件时,它将失败。您声称希望它“应该打破循环”。要简单地跳过一条记录,请使用
next if-mail.nil?
也许我描述得不对。如果没有名为“email”、“email”等列,我想打破循环,甚至不启动循环。如果在定义的列中找到记录,我的邮件变量只是一封电子邮件,但如果没有列,它将始终为零。谢谢,这就是我要找的。我观察到,如果将其放入循环中,将大大降低导入速度。我使用了您的想法并创建了自己的方法来跳过循环内的实现。我会更新我的帖子。
data = CSV.read("your.csv", headers: true, return_headers: true)
(0..(data.length-1)).each do |row|
   if  data[row].header_row? then
      p "yes header!"
   end
end