Convert CSV to array?

Any ideas on how to convert this CSV to a ruby ​​array using vim?

CSV launch:

Year,Make,Model
1997,Ford,E350
2000,Mercury,Cougar

      

Desired array:

car_info = [
  {'Year' => '1997', 'Make' => 'Ford', 'Model' => 'E350'},
  {'Year' => '2000', 'Make' => 'Mercury', 'Model' => 'Cougar'},
]

      

I have> 2000 records like the CSV above and would like it to quickly reformat it for use in my Rails application. I would love to use vim, but I am also open to other options.

+3


source to share


2 answers


FasterCSV.read("path/to/file.csv", :headers => true).map do |row|
  { "Year" => row[0], "Make" => row[1], "Model" => row[2] }
end

      



PS: install the faster_csv

gem

+6


source


In vim, you can use global search and replace with regex:

:g/\(.*\),\(.*\),\(.*\)/s//{'Year' => '\1', 'Make' => '\2', 'Model' => '\3'}/g

      



Then edit the first and last lines of the resulting file accordingly.

+4


source







All Articles