简体   繁体   中英

Return CSV Headers in Ruby

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

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 only works if :headers is true but it doesn't work the way you think it does.

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

Output:

ID: 1
Name: foo
1st col: 1
2nd col: foo
---
ID: 2
Name: bar
1st col: 2
2nd col: bar
---

I think you want headers: false

And if that fails, you can always skip the first line (does foreach return an iterator?)

CSV.foreach(file).each_with_index do |row, idx|


end

Also, it's just semantics, but foreach returns a row, not a column

You could also use CSV.table to read the .csv file into a table.

 datatable = CSV.table("file path")

and

 puts datatable.headers()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM