How to get headers from a CSV.read on a CSV file with only a header row in ruby -


so, i've been messing around csv files in ruby, , i've come across issue. in testing, call of x = csv.read(file, headers:true) on file contains header row return table, that, when converted array, returns [[]], , calling x.headers returns []. can circumvent problem setting return_headers:true, don't want file return headers, want headers. when add in fake, second row, x.headers returns headers, , :return_headers not need set true.

here code before , after adding row visualize issue.

with headers:true, return_headers:true on csv file 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 headers:true on csv file header row:

b = csv.read("june.csv", headers:true) #<csv::table mode:col_or_row row_count:1> b[0] # => nil b.headers # => [] 

with headers:true on csv file 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 csv file have have second row, because program intends build on it. doing wrong? intended behavior, or problem in setup, somehow? have read headers, , read behavior like? i've searched while, still having trouble

the behavior experiencing expected. similar question 2 years ago had answer pointed out same issue you're having. person opened bug report ruby ruby devs responded , rejected it. , according people technically not well-formed csv.

however, agree , person opened bug. headers: true option should fill out csv.headers regardless of whether there data on following lines or not. current behavior seems baffling , lead bugs in code.

as quick fix issue pass return_headers: true , begrudgingly skip on first entry in result, header row.


Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo