Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert CSV to Array?

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

Starting CSV:

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 entries like the CSV above, and I'd love a way to quickly re-format it for use in my Rails app. I'd like to use vim, but I'm open to other options too.

like image 984
Sauce McBoss Avatar asked Feb 16 '26 16:02

Sauce McBoss


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 faster_csv gem

like image 111
Harish Shetty Avatar answered Feb 18 '26 04:02

Harish Shetty


In vim, you can use global search and replace with a regular expression:

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

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

like image 40
Thilo Avatar answered Feb 18 '26 04:02

Thilo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!