ruby-on-rails - Ruby 遍历 CSV 行并绕过值

标签 ruby-on-rails ruby csv

我有一个包含 4 列的电子表格,我正在将结果保存到数据库中。我想要的是当涉及到包含 "string" 的单元格 d 时绕过此行并保存下一行等等。

这是我的模型代码

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     

提前致谢。

最佳答案

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 将跳过当前循环迭代的其余部分; =~ 将检查正则表达式是否匹配。

关于ruby-on-rails - Ruby 遍历 CSV 行并绕过值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45829188/

相关文章:

php - 如何在服务器上用 PHP 从 MySQL 查询中保存 CSV 文件

python - 用数组计算 numpy.mean?

ruby-on-rails - 在 mongo 分片环境中排序会降低性能

ruby-on-rails - RSpec 夹具未加载

ruby - ChefSpec 和 Ark 资源测试

ruby - Linux 主机的建议

ruby-on-rails - 有人知道在 Amazon S3 上存储 Rails 页面缓存的简单方法吗?

php - 跨不同子域(但不是全部)进行身份验证

ruby-on-rails - Rails Controller 中的 CORS 在 before_filter 或 after_filter 中?

javascript - 有没有办法从 csv 中获取文本格式?