Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get headers from a CSV file in ruby

I need to validate headers in a CSV file before parsing data in it.

# convert the data into an array of hashes
CSV::Converters[:blank_to_nil] = lambda do |field|
  field && field.empty? ? nil : field
end
csv = CSV.new(file, :headers => true, :header_converters => :symbol, :converters => [:all, :blank_to_nil])
csv_data = csv.to_a.map {|row| row.to_hash }

I know I can use headers method to get the headers

    headers = csv.headers

But the problem with headers method is it "Returns nil if headers will not be used, true if they will but have not yet been read, or the actual headers after they have been read."

So if I put headers = csv.headers above csv_data = csv.to_a.map {|row| row.to_hash } line headers is true and if I put it after reading data, headers contain headers row in an array. It imposes an order of instructions on my method which is very hard to test and is bad programming.

Is there a way to read headers row without imposing order in this scenario? I'm using ruby 2.0.

like image 817
Zeeshan Avatar asked Jan 12 '14 18:01

Zeeshan


People also ask

How do I get CSV headers in Ruby?

The CSV module's 'shift' method While the CSV module has options to read in or skip the headers when accessing a CSV file by adding the argument of “headers: true” to a read, open or new method call, this does not return the headers. Instead, it determines if the headers will be treated like other rows and be read.

Does CSV file has header?

CSV and spreadsheet content rules. Each row in the file must contain the same number of cells. This rule also applies to the header row. The first row must contain column headers.


1 Answers

CSV.open(file_path, &:readline)
like image 109
oozzal Avatar answered Sep 30 '22 21:09

oozzal