1

我有一个格式如下的 CSV 文件:

name,color,tasty,qty
apple,red,true,3
orange,orange,false,4
pear,greenish-yellowish,true,1

如您所见,Ruby OO 世界中的每一列都代表多种类型——字符串、字符串、布尔值、整数。

现在,最终,我想解析文件中的每一行,确定适当的类型,然后通过 Rails 迁移将该行插入到数据库中。例如:

Fruit.create(:name => 'apple', :color => 'red', :tasty => true, :qty => 3)

帮助!

4

1 回答 1

5

对于 Ruby 1.8:

require 'fastercsv'

FasterCSV.parse(my_string, :headers => true) do |row|
  Fruit.create!(
    :name => row['name'],
    :color => row['color'],
    :tasty => row['tasty'] == 'true',
    :qty => row['qty].to_i
  )
end

对于 Ruby 1.9,只需重命名FasterCSVCSV和:fastercsvcsv

require 'csv'

CSV.parse(my_string, :headers => true) do |row|
  # same as ruby-1.8
end
于 2010-04-09T18:34:09.790 回答