Luigi
Luigi

Reputation: 5603

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.

Upvotes: 2

Views: 2123

Answers (3)

PranathCP
PranathCP

Reputation: 1

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

 datatable = CSV.table("file path")

and

 puts datatable.headers()

Upvotes: 0

Stefan
Stefan

Reputation: 114138

: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
---

Upvotes: 5

dancow
dancow

Reputation: 3388

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

Upvotes: 0

Related Questions