1

Trying to delete rows from the csv file here with Ruby without success.

How can I tell that all rows, where column "newprice" is empty, should be deleted?

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

Thanks!

1 Answer 1

1

Almost there. The table method changes the headers to symbols, and delete_if takes a block, the same way as each and open.

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
Sign up to request clarification or add additional context in comments.

1 Comment

Ah yes, I used the other block form and forgot about it. Corrected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.