Convert CSV file into array of hashes

Mythago picture Mythago · Jan 7, 2013 · Viewed 52.2k times · Source

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

Nathan Long picture Nathan Long · Mar 28, 2014

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?