我有一个格式如下的 CSV 文件:
name,color,tasty,qty
apple,red,true,3
orange,orange,false,4
pear,greenish-yellowish,true,1
如您所见,Ruby OO 世界中的每一列都代表一种类型的混合——string、string、boolean、int。
现在,最终,我想解析文件中的每一行,确定合适的类型,然后通过 Rails 迁移将该行插入到数据库中。例如:
Fruit.create(:name => 'apple', :color => 'red', :tasty => true, :qty => 3)
帮助!
最佳答案
对于 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,只需将 FasterCSV
重命名为 CSV
并将 fastercsv
重命名为 csv
:
require 'csv'
CSV.parse(my_string, :headers => true) do |row|
# same as ruby-1.8
end
关于ruby-on-rails - 进入那个数据库!使用 Ruby 解析 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2609891/