3
require 'csv'    

CSV.foreach(filename, :headers => true) do |row|
  if column3 = true || column 4 = true
    Model.create!(row.to_hash)
  else
    skip
  end
end

首先,有没有办法只在 期间抓取某些列row.to_hash

其次,我使用if语句是获取特定行的最佳方式吗?我可以将整个 CSV 加载到某种临时表中,然后获取我需要的东西吗?

4

1 回答 1

4

row.to_hash将根据标头生成属性哈希。要选择一组特定的属性,您应该使用 slice。

>> row.to_hash # { :attr1 => 'val1', :attr2 => 'val2', :attr3 => 'val3' }
>> row.to_hash.slice(:attr1, :attr2) # { :attr1 => 'val1', :attr2 => 'val2' }

关于您的第二个问题:是的,您仍然需要加载整个 csv 并检查每一行。

于 2013-02-24T04:16:52.740 回答