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?
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With