Home > database >  How to make user input to csv update the actual csv file
How to make user input to csv update the actual csv file

Time:10-18

In ruby 3.1.2, I have this csv file:

make,model,color,doors,email
dodge,charger,black,4,[email protected]
ford,focus,blue,5,[email protected]
nissan,350z,black,2,[email protected]
mazda,miata,white,2,[email protected]
honda,civid,brown,4,[email protected]
corvette,stingray,red,2,[email protected]
ford,fiesta,blue,5,[email protected]
bmw,m4,black,2,[email protected]
audi,a5,blue,2,[email protected]
subaru,brz,black,2,[email protected]
lexus,rc,black,2,[email protected]

My current program allows a user to input an email and from that email it will go to that line and change the value of the model of a car, and then print out the csv onto the screen. What can be done to make the code also update the actual CSV file in the directory?

This is my code:

require "csv"

csv = CSV.read('cars.csv', headers: true)
print "Enter an email: \n> "
demo = gets.chomp
#print csv.find {|row| row['email'] == demo}
got = csv.find {|row| row['email'] == demo}
p got

p got.fields
p got['model']
got['model'] = 'rcf'
p got['model']
p got.fields
#prints out the csv file 
puts csv.to_s

if my coding approach is different and if there's a better way don't hesitate to change any of my coding or completely not use it and go another path, please comment the code

CodePudding user response:

Please refer below for your reference:

csv = CSV.read('cars.csv', headers: true)
print "Enter an email: \n> "
demo = gets.chomp
csv.map{|row| row['model'] = 'rcf' if row['email'] == demo}

puts csv.to_s

CSV.open("cars.csv", "wb") do |new_csv|
  new_csv << %w[make model color doors email] 
  csv.each do |row|
    new_csv << row
  end
end

I hope this will help you.

  • Related