In Ruby 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]
and this is my code:
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
Having this code, how can I make it if the user enters an invalid email (misspelled email or anything that doesn't match an email from the CSV file), it asks to enter a valid one since the one they typed isn't an email from the CSV file
CodePudding user response:
Load table
first.
Now you can use #any?
to see if any rows contain that email address.
table.any? { |row| row["email"] == delete_car }
Now, just do this in a loop, breaking the loop when the input email address is in the table.
delete_car = loop do
email = gets.chomp
break email if table.any? { |row| row["email"] == email }
puts "Invalid input. Try again."
end
You may also wish to generate a set of valid email addresses. If you think you'll need to loop several times, this may lead to better performance.
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