Given the following CSV file, how would you remove all rows that contain the word \'true\' in the column \'foo\'?
Date,foo,bar
2014/10/31,true,derp
2014/10/
You might want to filter rows in a ruby manner:
require 'csv'
csv = CSV.parse(File.read(@csvfile), {
:col_sep => ",",
:headers => true
}
).collect { |item| item[:foo] != 'true' }
Hope it help.
You should be able to use CSV::Table#delete_if, but you need to use CSV::table instead of CSV::read
, because the former will give you a CSV::Table object, whereas the latter results in an Array of Arrays. Be aware that this setting will also convert the headers to symbols.
table = CSV.table(@csvfile)
table.delete_if do |row|
row[:foo] == 'true'
end
File.open(@csvfile, 'w') do |f|
f.write(table.to_csv)
end