在ruby 3.1.2中,我有一个csv文件:
make,model,color,doors,email
dodge,charger,black,4,practice1@whatever.com
ford,focus,blue,5,practice2@whatever.com
nissan,350z,black,2,practice3@whatever.com
mazda,miata,white,2,practice4@whatever.com
honda,civid,brown,4,practice5@whatever.com
corvette,stingray,red,2,practice6@whatever.com
ford,fiesta,blue,5,practice7@whatever.com
bmw,m4,black,2,practice8@whatever.com
audi,a5,blue,2,practice9@whatever.com
subaru,brz,black,2,practice10@whatever.com
lexus,rc,black,2,practice11@whatever.com
我当前的程序允许用户输入一封电子邮件,然后从该电子邮件转到该行,更改汽车型号的值,然后将csv打印到屏幕上。如何使代码也更新目录中的实际CSV文件?
这是我的代码:
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
如果我的编码方法不同,如果有更好的方法,不要犹豫,改变我的任何编码,或者完全不使用它,走另一条路,请评论代码
请参考以下内容:
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
我希望这对你有帮助。