Ruby csv - 如果列为空,则删除行

时间:2015-06-27 20:21:29

标签: ruby-on-rails ruby csv

尝试使用Ruby从csv文件中删除行而没有成功。

我如何判断所有行,列" newprice"是空的,应该删除吗?

require 'csv' 
guests = CSV.table('new.csv', headers:true)

guests.each do |guest_row|
  p guests.to_s 
end

price = CSV.foreach('new.csv', headers:true) do |row|
  puts row['newprice'] 
end 

guests.delete_if('newprice' = '')

File.open('new_output.csv', 'w') do |f|
  f.write(guests.to_csv)
end

谢谢!

1 个答案:

答案 0 :(得分:1)

几乎就在那里。 table方法将标题更改为符号,delete_if采用块,与eachopen相同。

require 'csv' 
guests = CSV.table('test.csv', headers:true)

guests.each do |guest_row|
  p guest_row.to_s 
end

guests.delete_if do |row| 
  row[:newprice].nil?
end

File.open('test1.csv', 'w') do |f|
  f.write(guests.to_csv)
end