views:

607

answers:

3

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.

+3  A: 

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
Couldn't get a url to open within FasterCSV.read
Jeffrey
Also tried to read a local file and I got a compile error:"odd number list for Hash"
Jeffrey
Odd number list for hash should have nothing to do with FasterCSV. Any chance you're using braces to bookend your if blocks?
EmFi
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
figured out a solution, see below -- thanks for your help
Jeffrey
A: 

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
A: 

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

PanosJee