0

I'm trying to get fastercsv setup so that rather than parsing each row, it will place each column into an multi array.

CSV import file:
id, first name, last name, age
1, joe, smith, 11
2, jane, doe, 14

Save to array named people:
people[0][0] would equal id
people[2][1] would equal jane

This is what I currently have:

url = 'http://url.com/file.csv'
open(url) do |f|
  f.each_line do |line|
    FasterCSV.parse(line) do |row|
      row
    end
  end
end

Any help is appreciated.

2
  • Why a multi-dimensional array? What is wrong with an array of hashes which is much nicer to read. Commented Nov 2, 2009 at 11:48
  • I wanted a multi-dimensional array setup for each column because I don't need to store the data in active-record nor do I know what the column names will be, I want to take the array and build a xml file out of it so that each column name will be each column's attribute... if that makes sense :) Commented Nov 2, 2009 at 16:05

3 Answers 3

3

Have you read the FasterCSV documentation?

If you did, you would know that the easiest way to do what you want is:

people = FasterCSV.read('http://url.com/file.csv')
Sign up to request clarification or add additional context in comments.

3 Comments

Also tried to read a local file and I got a compile error: "odd number list for Hash"
Odd number list for hash should have nothing to do with FasterCSV. Any chance you're using braces to bookend your if blocks?
Also you've got to go through some tricks to read from a URL, see this question: stackoverflow.com/questions/435634/…
0

Thanks EmFi, with your help I was able to come up with a solution.

This takes a remote url csv file and loads it into a multi-dimensional array, based on columns.

require 'rio'
require 'fastercsv'

url = 'http://remoteurl.com/file.csv'
people = FasterCSV.parse(rio(url).read)

Comments

0

You can use CsvMapper on top of FasterCSV It s a life saver

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.