DZone 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

Snippets has posted 5883 posts at DZone. View Full User Profile

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

04.25.2007
| 20964 views |
  • submit to reddit
        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

Snippets Manager replied on Sat, 2007/09/29 - 2:37pm

I think I got it, change first line to: csv_data = CSV.open('data.tab', 'r', ?\t)

Snippets Manager replied on Sat, 2007/09/29 - 2:37pm

How would this change if the file was tab delimited, rather than comma delimited?