如何将文件设置为不提取 csv 文件中的标题?我已经尝试过:
CSV.foreach(email_response_file, :col_sep => "\t", :return_headers => false) do |column|
....
end
但是,无论我将 :return_headers
设置为 true 还是 false,我仍然会提取 header 。我怎样才能摆脱它们?我假设我的问题是我正在使用的 .foreach
方法。
最佳答案
:return_headers
仅当 :headers
为 true
时才有效,但它不会按照您想象的方式工作。
如果您的 CSV 数据包含标题行,只需设置 headers: true
并且第一行不会作为数据行返回。相反,它被解析并允许您通过其 header 访问字段(如哈希):
require 'csv'
data=<<-eos
id,name
1,foo
2,bar
eos
CSV.parse(data, headers: true) do |row|
puts "ID: " + row["id"]
puts "Name: " + row["name"]
puts "1st col: " + row[0]
puts "2nd col: " + row[1]
puts "---"
end
输出:
ID: 1
Name: foo
1st col: 1
2nd col: foo
---
ID: 2
Name: bar
1st col: 2
2nd col: bar
---
关于ruby - 在 Ruby 中返回 CSV header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19327554/