开发者

FasterCSV: columns into an array -- rails

开发者 https://www.devze.com 2022-12-10 10:47 出处:网络
I\'m trying to get fastercsv setup so that rather than parsing each row, it will place each column into an multi array.

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开发者_如何学Python) do |f|
  f.each_line do |line|
    FasterCSV.parse(line) do |row|
      row
    end
  end
end

Any help is appreciated.


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')


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)


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

0

精彩评论

暂无评论...
验证码 换一张
取 消