在rails迭代CSV,记录错误但不停止循环

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在rails迭代CSV,记录错误但不停止循环相关的知识,希望对你有一定的参考价值。

我想迭代一个格式错误的CSV,如下所示:

“col1”,1000,“col2”,“malformed”col3“,”col4“

“col1”,1000,“col2”,“col3”,“col4”

“col1”,1000,“col2”,“”格式错误的col3,“col4”

使用Rails所以,当找到一行中的错误时,抛出CSV::MalformedCSVError但循环不会停止。

我找了不同的解决方案但是直到知道才行。 :(

目前我有这样的方法:

def iterate_csv
  puts 'lets iterate!!'
  CSV.foreach(@file) { |line| 
    begin
      puts 'loop is on fire...'
      # handle line here
    rescue CSV::MalformedCSVError => e
      puts e
      # handle malformed row here...
    next
    end
  }
end

所有的帮助,我发现谷歌搜索没有帮助..任何输入赞赏!

答案

如果你想要停止循环你应该把breakinstead的next

以上是关于在rails迭代CSV,记录错误但不停止循环的主要内容,如果未能解决你的问题,请参考以下文章