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 = FasterCSV.read( '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[ [...]
ruby csv to structured hash