So, I've been messing around with CSV files in Ruby, and I've come across an issue. In my testing, a call of x = CSV.read(file, headers:true) on a file which only contains the header row will return a table, that, when converted to an array, returns [[]], and calling x.headers returns []. I can circumvent this problem by setting return_headers:true, but I don't actually want the file to return its headers, I just want the headers. When I add in a fake, second row, x.headers actually returns the headers, and :return_headers does not need to be set to true.
Here is some code from before and after adding a row to help visualize the issue.
With headers:true, return_headers:true on a csv file with only the header row:
a = CSV.read("June.csv", headers:true, return_headers:true) # <CSV::Table mode:col_or_row row_count:1>
a[0] # <CSV::Row "Day":"Day" "Time":"Time">
a.headers # => ["Day", "Time"]
With only headers:true on a csv file with only the header row:
b = CSV.read("June.csv", headers:true) #<CSV::Table mode:col_or_row row_count:1>
b[0] # => nil
b.headers # => []
With only headers:true on a csv file with the fake second row:
c = CSV.read("June.csv", headers:true) #<CSV::Table mode:col_or_row row_count:2>
c.headers # => ["Day", "Time"]
c["Day"] # => ["6/1"]
I can't depend on the CSV file I have to always have a second row, because my program intends to build on it. What am I doing wrong? Is this the intended behavior, or is the problem in my setup, somehow? Do I have to do a read just for the headers, and then another read to get the behavior I would like? I've searched for a good while, but am still having trouble