Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Turn CSV with headers into Array of Hashes (in 5 lines or less) (See related posts)

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

Comments on this post

delgaudm posts on Sep 29, 2007 at 14:46
How would this change if the file was tab delimited, rather than comma delimited?
delgaudm posts on Oct 02, 2007 at 11:46
I think I got it, change first line to:
csv_data = CSV.open('data.tab', 'r', ?\t)

You need to create an account or log in to post comments to this site.


Click here to browse all 4861 code snippets

Related Posts