在Ruby中返回CSV标头

在Ruby中返回CSV标头

本文介绍了在Ruby中返回CSV标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何设置我的文件不拉入csv文件中的标头?我已经尝试过了:

How can I set my file to not pull in the headers in my csv file? I have tried this:

CSV.foreach(email_response_file, :col_sep => "\t", :return_headers => false) do |column|
  ....
end

但是,无论我将:return_headers设置为true还是false,我仍然会插入标题.我该如何摆脱它们?我认为我的问题是我正在使用的.foreach方法.

However, regardless of whether I set :return_headers to true or false I still pull in the headers. How can I get rid of them? I assume my issue is the .foreach method I am using.

推荐答案

:return_headers仅在:headerstrue的情况下有效,但它并不像您认为的那样起作用.

:return_headers only works if :headers is true but it doesn't work the way you think it does.

如果您的CSV数据包含标题行,则只需设置headers: true,第一行就不会作为数据行返回.而是对其进行解析,并允许您通过其标题(例如哈希)访问字段:

If your CSV data contains a header row, just set headers: true and the first row is not returned as a data row. Instead it is parsed and allows you to access a field by its header (like a hash):

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中返回CSV标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 16:13