Over a million developers have joined DZone.

Turn CSV With Headers Into Array Of Hashes (in 5 Lines Or Less)

·
This assumes you have a CSV file whose first line are headings/labels for the individual columns.


require 'csv'

csv_data = CSV.read 'data.csv'
headers = csv_data.shift.map {|i| i.to_s }
string_data = csv_data.map {|row| row.map {|cell| cell.to_s } }
array_of_hashes = string_data.map {|row| Hash[*headers.zip(row).flatten] }
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}