在 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 檔案對應于電子郵件的行。我當前的代碼執行此操作,但沒有檢查用戶是否輸入了有效的電子郵件地址,這就是我堅持的部分。這是我的代碼:
def delete_from_data
print "\nTo delete a car, enter the email (this is case sensitive): \n> "
delete_car = gets.chomp
#this allows me to delete a certain row based on email
table = CSV.table("cars.csv")
table.delete_if do |row|
row[:email] == delete_car
end
File.open("cars.csv", "w") do |f|
f.write(table.to_csv)
end
#this shows the updated student roster after deleting user
puts "\nThis is the updated roster after deleting: #{delete_car}"
end
例如,如果用戶輸入“ [email protected]”,則 CSV 檔案中的整行將被洗掉。但是,如果用戶從 CSV 檔案中輸入有效電子郵件地址以外的任何其他內容,它仍然會運行。
uj5u.com熱心網友回復:
您應該閱讀CSV::Table 的檔案并注意它有一個#each方法可以讓您遍歷行。事實上,很多 Ruby 容器類都有一個#each方法,所以如果你想在 Ruby 中做任何有意義的事情,你需要熟悉它。
像這樣的東西應該作業:
email_found = false
while !email_found
email = gets.chomp
table.each do |row|
if row[:email] == email
email_found = true
end
end
end
請注意,這并不意味著是漂亮或優化的代碼,而是簡單的初學者級代碼。
要獲得額外的榮譽,請了解 Ruby 的 Enumerable 模塊并使用.any?而不是.each.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/515536.html
標籤:红宝石CSV
上一篇:將影像圖表轉換為陣列
