且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从使用Ruby的CSV中删除一行

更新时间:2023-12-04 11:57:04

您应该可以使用CSV::Table#delete_if,但您需要使用 CSV: :table 而不是 CSV :: read ,因为前者会为您提供一个CSV :: Table对象,而后者结果在数组数组。请注意,此设置也会将标题转换为符号。

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