Mythago Mythago - 16 days ago 8
Ruby Question

Convert CSV file into array of hashes

I have a csv file, some hockey stats, for example:

09.09.2008,1,HC Vitkovice Steel,BK Mlada Boleslav,1:0 (PP)
09.09.2008,1,HC Lasselsberger Plzen,RI OKNA ZLIN,6:2
09.09.2008,1,HC Litvinov,HC Sparta Praha,3:5


I want to save them in an array of hashes. I don't have any headers and I would like to add keys to each value like
"time" => "09.09.2008"
and so on. Each line should by accessible like
arr[i]
, each value by for example
arr[i]["time"]
. I prefer
CSV
class rather than
FasterCSV
or
split
. Can you show the way or redirect to some thread where a similar problem was solved?

Answer

You can use the Ruby CSV parser to parse it, and then use Hash[ keys.zip(values) ] to make it a hash.

Example:

test = '''
09.09.2008,1,HC Vitkovice Steel,BK Mlada Boleslav,1:0 (PP)
09.09.2008,1,HC Lasselsberger Plzen,RI OKNA ZLIN,6:2
09.09.2008,1,HC Litvinov,HC Sparta Praha,3:5
'''.strip

keys = ['time', etc... ]
CSV.parse(test).map {|a| Hash[ keys.zip(a) ] }
Comments