ruby - 在 Ruby 中返回 CSV header

标签 ruby csv

如何将文件设置为不提取 csv 文件中的标题?我已经尝试过:

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

但是,无论我将 :return_headers 设置为 true 还是 false,我仍然会提取 header 。我怎样才能摆脱它们?我假设我的问题是我正在使用的 .foreach 方法。

最佳答案

:return_headers 仅当 :headerstrue 时才有效,但它不会按照您想象的方式工作。

如果您的 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/

相关文章:

ruby - 使用 PG ruby​​ 运行错误查询时如何获取 nill 或 messege 而不是应用程序失败

ruby-on-rails - ruby on rails 模型验证中的浮点精度

ruby-on-rails - Rails - 当我尝试删除或发布操作时,sidekiq Web 界面显示禁止

c# - 写入csv文件

ruby - 如何将 gem 嵌入到 RubyCocoa 应用程序中?

php - 将数据导出为CSV格式并将csv文件存储在服务器中

bash - append 到 Bash 中的同一行

c# - 如何使用 C# 处理 CSV 文件中的换行符?

mysql - 将csv数据导入Mysql数据库

ruby - 在 Ruby Volt 中存储图片