Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 852
Mythago Avatar asked Jan 07 '13 16:01

Mythago


1 Answers

Just pass headers: true

CSV.foreach(data_file, headers: true) do |row|   puts row.inspect # hash end 

From there, you can manipulate the hash however you like.

(Tested with Ruby 2.0, but I think this has worked for quite a while.)

Edit

You say you don't have any headers - could you add a header line to the beginning of the file contents after reading them?

like image 123
Nathan Long Avatar answered Sep 20 '22 18:09

Nathan Long