gpt4 book ai didi

ruby-on-rails - 进入那个数据库!使用 Ruby 解析 CSV

转载 作者:太空宇宙 更新时间:2023-11-03 17:41:26 25 4
gpt4 key购买 nike

我有一个格式如下的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com