FasterCSV:列到数组 - rails

时间:2009-11-02 05:29:37

标签: ruby-on-rails arrays csv import fastercsv

我正在尝试设置更快的设置,以便不是解析每一行,而是将每列放入一个多数组中。

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

这就是我目前所拥有的:

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

感谢任何帮助。

3 个答案:

答案 0 :(得分:3)

您是否阅读过FasterCSV documentation?

如果你这样做,你会知道做你想做的最简单的方法是:

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

答案 1 :(得分:0)

感谢EmFi,在您的帮助下,我能够提出解决方案。

这需要一个远程url csv文件,并根据列将其加载到一个多维数组中。

require 'rio'
require 'fastercsv'

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

答案 2 :(得分:0)

您可以在FasterCSV之上使用CsvMapper 这是一个救生员