Convert CSV file into array of hashes Convert CSV file into array of hashes ruby ruby

Convert CSV file into array of hashes


Just pass headers: true

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

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?


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:209.09.2008,1,HC Litvinov,HC Sparta Praha,3:5'''.stripkeys = ['time', etc... ]CSV.parse(test).map {|a| Hash[ keys.zip(a) ] }


This is a fantastic post by Josh Nichols which explains how to do what you're asking.

To summarize, here his code:

csv = CSV.new(body, :headers => true, :header_converters => :symbol, :converters => [:all, :blank_to_nil])csv.to_a.map {|row| row.to_hash }=> [{:year=>1997, :make=>"Ford", :model=>"E350", :description=>"ac, abs, moon", :price=>3000.0}, {:year=>1999, :make=>"Chevy", :model=>"Venture \"Extended Edition\"", :description=>nil, :price=>4900.0}, {:year=>1999, :make=>"Chevy", :model=>"Venture \"Extended Edition, Very Large\"", :description=>nil, :price=>5000.0}, {:year=>1996, :make=>"Jeep", :model=>"Grand Cherokee", :description=>"MUST SELL!\nair, moon roof, loaded", :price=>4799.0}]

So, you could save the body of your CSV file into a string called body.

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

And then run his code as listed above on it.