解析CSV文件时忽略标题行

Dee*_*ane 13 csv ruby-on-rails-3

在进行CSV解析时,如何在轨道上的ruby中忽略CSV文件的标题行!! 有任何想法吗

Dav*_*low 26

如果你使用ruby 1.8.X和FasterCSV,它有一个' headers '选项:

csv = FasterCSV.parse(your_csv_file, {:headers => true}) #or false if you do want to read them
Run Code Online (Sandbox Code Playgroud)

如果您使用的是ruby 1.9.X,则默认库基本上是FasterCSV,因此您可以执行以下操作:

csv = CSV.parse(your_csv_file, {headers: true})
Run Code Online (Sandbox Code Playgroud)

  • 注意`CSV.parse your_csv_content`和`CSV.parse your_csv_content,headers:true`返回不同的对象.首先是数组数组,第二个是`CSV :: Row`对象的数组http://stackoverflow.com/a/37856698/473040 (2认同)

Che*_*eng 6

csv = CSV.read("file")

csv.shift # <-- kick out the first line

csv # <-- the results that you want
Run Code Online (Sandbox Code Playgroud)


Dee*_*ane 1

我已经找到了上述问题的解决方案。这是我在 ruby​​ 1.9.X 中完成的方法。

csv_contents = CSV.parse(File.read(file))
csv_contents.slice!(0)
csv=""
csv_contents.each do |content|
    csv<<CSV.generate_line(content)
end
Run Code Online (Sandbox Code Playgroud)