In Ruby 3.1.2, using 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]
If the user does not enter an email address that is part of the CSV file above or anything that does not equal an email, the program asks the user to enter a valid email until they actually do, and then update the CSV file with the deleted row corresponding to the email. My current code does this but there is no checking if the user enters a valid email address or not and that is the part I am stuck on. 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
for example, if the user enters "[email protected]
", then that whole row from the CSV file gets deleted. But if a user enters anything else other than a valid email address from the CSV file, it still runs.
CodePudding user response:
You should read the documentation of CSV::Table and notice that it has a #each
method that allows you to iterate over the rows. In fact, lots of Ruby container classes have a #each
method so you will need to get familiar with it if you want to do anything meaningful in Ruby.
Something like this should work:
email_found = false
while !email_found
email = gets.chomp
table.each do |row|
if row[:email] == email
email_found = true
end
end
end
Note that this is not meant to be beautiful or optimized code, but simple, beginner-level code.
For extra credit, learn about Ruby's Enumerable module and use .any?
instead of .each
.