How to remove a row from a CSV with Ruby

前端 未结 2 1889
别那么骄傲
别那么骄傲 2021-01-13 09:59

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/         


        
2条回答
  •  情书的邮戳
    2021-01-13 10:25

    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
    

提交回复
热议问题