Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

DZone's Guide to

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

·
Free Resource
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:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}