Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the easiest way to get the headers from a CSV file in Ruby?

Tags:

parsing

ruby

csv

All I need to do is get the headers from a CSV file.

file.csv is:

"A", "B", "C"  
"1", "2", "3"

My code is:

table = CSV.open("file.csv", :headers => true)

puts table.headers

table.each do |row|
  puts row 
end

Which gives me:

true
"1", "2", "3"

I've been looking at Ruby CSV documentation for hours and this is driving me crazy. I am convinced that there must be a simple one-liner that can return the headers to me. Any ideas?

like image 456
Anthony To Avatar asked Aug 08 '13 00:08

Anthony To


1 Answers

It looks like CSV.read will give you access to a headers method:

headers = CSV.read("file.csv", headers: true).headers
# => ["A", "B", "C"]

The above is really just a shortcut for CSV.open("file.csv", headers: true).read.headers. You could have gotten to it using CSV.open as you tried, but since CSV.open doesn't actually read the file when you call the method, there is no way for it to know what the headers are until it's actually read some data. This is why it just returns true in your example. After reading some data, it would finally return the headers:

  table = CSV.open("file.csv", :headers => true)
  table.headers
  # => true
  table.read
  # => #<CSV::Table mode:col_or_row row_count:2>
  table.headers
  # => ["A", "B", "C"]
like image 55
Dylan Markow Avatar answered Oct 03 '22 02:10

Dylan Markow