在Ruby中,我有一个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
这是我的代码:
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
有了这个代码,如果用户输入了一封无效的电子邮件(拼写错误的电子邮件或任何与CSV文件中的电子邮件不匹配的邮件(,它会要求输入一封有效的电子邮件,因为他们输入的不是CSV文件中的电子邮件,我该怎么办
首先加载table
。
现在,您可以使用#any?
查看是否有任何行包含该电子邮件地址。
table.any? { |row| row[:email] == delete_car }
现在,只需在循环中执行此操作,打破循环并在输入电子邮件地址位于表中时返回输入电子邮件。
delete_car = loop do
email = gets.chomp
break email if table.any? { |row| row[:email] == email }
puts "Invalid input. Try again."
end
您可能还希望生成一组有效的电子邮件地址。如果您认为需要循环几次,这可能会带来更好的性能。
valid_emails = table.map { |row| row[:email] }.to_set
delete_car = loop do
email = gets.chomp
break email if valid_emails.include?(email)
puts "Invalid input. Try again."
end