ruby csv to structured hash

I had a csv like this:

object color flavor shape
apple red sweet round
banana yellow sweet long
lemon yellow sour round

and I wanted a ruby hash structured like this:

'apple'=> { 'color'=>'red', 'flavor'=>'sweet', 'shape'=>'round'},
'banana'=> { 'color'=>'yellow', 'flavor'=>'sweet', 'shape'=>'long'},
'lemon'=> { 'color'=>'yellow', 'flavor'=>'sour', 'shape'=>'round'}

So I wrote this, which does the job:

require "faster_csv"

def csv_to_structured_hash
	arr_of_arrs = 'your.csv' )
	stuff = {}
	header = arr_of_arrs.shift
		arr_of_arrs.each_with_index do |row, i|
		thing = { row[0] => {} }
			header.each_with_index do |col, header_index|
			thing[ row[0] ][ header[header_index] ] = row[ header_index]
		stuff.update( thing )
	return stuff
This entry was posted in rails, ruby. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

One Comment

  1. Tilo
    Posted August 8, 2012 at 12:17 pm | Permalink

    check out the smarter_csv Gem :

Post a Comment

Your email is never published nor shared. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>