Graham Jackson Graham Jackson - 4 months ago 21
Ruby Question

Ignore rows with blank values while importing a CSV in rails application

I have an app where I allow users to import CSV data.

Everything was working until users started importing data with blank rows in the CSV file. I am using the following to grab the rows out of the CSV file:

CSV.readlines(import_file, headers: true, skip_blanks: true)

I thought that if I added the option to skip_blanks that it would do that but it hasn't. Any ideas on how I can ignore the blank rows.



This should work, skip_blanks: true).reject { |row| row.all?(&:nil?) }


You requested for readlines, it calls open in the CSV source code in the end but this is it:

CSV.readlines(import_file, skip_blanks: true).reject { |row| row.all?(&:nil?) } 

I feel open would perform better though I have not done any bench marking, skip_blanks: true, headers: true).reject { |row| row.to_hash.values.all?(&:nil?) }

CSV.readlines(import_file, skip_blanks: true, headers: true).reject { |row| row.to_hash.values.all?(&:nil?) }

The above returns a collection of CSV::Row objects