Bug #9582

CSV#headers not giving expected results.

Added by arup rakshit about 1 year ago. Updated 12 months ago.

[ruby-core:61154]
Status:Rejected
Priority:Normal
Assignee:-
ruby -v:- Backport:

Description

It seems something not working as expected in CSV. I tried to find the reason here , http://rxr.whitequark.org/mri/source/lib/csv.rb but I failed.

require 'csv'

content = <<_
key,fr
edit,Éditer
close,Fermer
_

File.write('test',content)

file = CSV.read('test', :headers => true)
file.headers # => ["key", "fr"]
file.to_a # => [["key", "fr"], ["edit", "Éditer"], ["close", "Fermer"]]

content = <<_
key,fr

edit,Éditer
close,Fermer
_

File.write('test1',content)

file = CSV.read('test1', :headers => true)
file.headers # => []  # <~~~~~~~~~~~ Is this a bug ?
file.to_a # => [[], [], ["edit", "Éditer"], ["close", "Fermer"]]

9582.patch Magnifier (870 Bytes) Thiago Lewin, 03/05/2014 05:16 AM

History

#1 Updated by Tomoyuki Chikanaga 12 months ago

  • Tracker changed from Backport to Bug
  • Project changed from Backport200 to Ruby trunk
  • ruby -v set to -

#2 Updated by Thiago Lewin 12 months ago

The CSV::Table#headers method just look at the first row of the table, if you enable the option ":return_headers" then should work.
In order to keep the API consistency, I attached a patch that iterates through the table until find a row with header information.

#3 Updated by James Gray 12 months ago

  • Status changed from Open to Rejected

Yeah, I also looked at making this change, but the behavior of returning just the first line is documented:

https://github.com/ruby/ruby/blob/trunk/lib/csv.rb#L672

I'm not sure if users of this library count on that or not. This change would alter the behavior of tables, so at the very least I think it would need to happen on a major version release.

Tables are also editable, so deleting rows affects the results of what this method returns.

Anyway, if you need the non-first row headers, you can always do:

header_row = table.find { |row| !row.headers.empty? }
headers = header_row && header_row.headers

Also available in: Atom PDF