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.

Jeffrey
  • 4,098
  • 11
  • 42
  • 66
  • Why a multi-dimensional array? What is wrong with an array of hashes which is much nicer to read. – Ryan Bigg Nov 02 '09 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 :) – Jeffrey Nov 02 '09 at 16:05

3 Answers3

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')
EmFi
  • 23,435
  • 3
  • 57
  • 68
  • Also tried to read a local file and I got a compile error: "odd number list for Hash" – Jeffrey Nov 02 '09 at 15:58
  • Odd number list for hash should have nothing to do with FasterCSV. Any chance you're using braces to bookend your if blocks? – EmFi Nov 02 '09 at 16:21
  • Also you've got to go through some tricks to read from a URL, see this question: http://stackoverflow.com/questions/435634/fastercsv-read-remote-csv-files – EmFi Nov 02 '09 at 16:21
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)
Jeffrey
  • 4,098
  • 11
  • 42
  • 66
0

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

PanosJee
  • 3,866
  • 6
  • 36
  • 49