2017-08-23 34 views
1

我有一个电子表格有4列,我将结果保存到数据库。我想要的是当涉及一个单元时,d,其中包含"string"绕过此行并保存下一行依此类推。红宝石遍历CSV行和绕过值

这是我的模型代码提前

def self.assign_row(row) 
    a, b, c, d = row 
    @c = c.slice(1,4) 
    Result.create(line: c, min: @c) 
end 

def self.import(file) 
    CSV.foreach(file.path) do |row| 
    result = Result.assign_row(row) 
    end 
end  

感谢。

回答

4
CSV.foreach(file.path) do |row| 

    # when it came to a cell 'd' that contain "string" bypass this row 
    next if row['d'] =~ /string/ 

    result = Result.assign_row(row) 
end 

next将跳过当前循环迭代的其余部分; =~将检查regexp是否匹配。

+0

非常感谢您的回复 这是我这 “ 类型错误在ResultsController#进口 字符串的隐式转换成整数” – Amr

+0

哦,你可能使用CSV没有头后得到。让它成为'行[3]'然后。 – Amadan

+0

TypeError(字符串不隐式转换为整数) result.rb:11:在'import' app/controllers/results_controller.rb:4:在'import' – Amr