2013-02-24 65 views
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期间只抓取某些列?从导入CSV的特定行和列

二,是我使用if声明抓取特定行的最佳方式吗? 我可以将整个CSV加载到某种排序表,然后抓住我需要的东西吗?

回答

4

row.to_hash将根据标题产生属性的散列。要选择一组特定的属性,应该使用切片。

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

关于第二个问题:是的,你仍然需要加载整个CSV,只是核对每行。

+0

你对我很好,jvnill。谢谢! – Dudo 2013-02-24 04:20:29