3

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.

2
  • Why don't you just read the file in and convert it to the object you want using Ruby? Commented Mar 18, 2012 at 18:46
  • 1
    That's a good idea -- could you post an example in the answers? Commented Mar 18, 2012 at 20:36

2 Answers 2

6
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

Sign up to request clarification or add additional context in comments.

2 Comments

+1. You could also use :headers => true when reading the CSV.
Awesome. This looks more promising than doing it by hand. Thanks!
4

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.

1 Comment

Thanks -- this looks like a good solution. Didn't know you could combine search with regex.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.