Project

General

Profile

Actions

Bug #9582

closed

CSV#headers not giving expected results.

Added by pritamdey (arup rakshit) over 10 years ago. Updated over 10 years ago.

Status:
Rejected
Assignee:
-
Target version:
-
ruby -v:
-
Backport:
[ruby-core:61154]

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"]]

Files

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

Updated by nagachika (Tomoyuki Chikanaga) over 10 years ago

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

Updated by tlewin (Thiago Lewin) over 10 years 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.

Updated by JEG2 (James Gray) over 10 years 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

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0