2

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.

3 Answers 3

5

: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
---
Sign up to request clarification or add additional context in comments.

1 Comment

Great - That explains it perfectly and solves the issue. I was definitely misunderstanding how :return_headers works. Thanks for the tip.
0

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

Comments

0

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

 datatable = CSV.table("file path")

and

 puts datatable.headers()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.