Ruby Build an Address Book in Ruby Input and Output Saving The Address Book

Sean Flanagan
Sean Flanagan
33,223 Points

Deleting a contact

Hi.

I thought about what Jason suggested about deleting a contact and I've come up with my own method:

def delete_contact
  if Contact.exist?("contacts.yml")
    @contacts = YAML.delete_file("contacts.yml")
  end
end

Will that work?

2 Answers

Cory Price
Cory Price
3,845 Points

I could be wrong, but I believe that you would need to correct your 2nd line for that to work, to look something like this:

if File.exist?("contacts.yml")

Seems to me that should work!

(late answer but)

I think the method we are using to save the file creates a new file/overwrites the file each time you exit and save, so unless you do something to the contacts array, the deletion is not going to be permanent.

To delete all the contacts could you just set @contacts equal to an empty array? or maybe use slice! over the entire range? Is there a preferred way of doing it?

For deleting just one contact, I ended up running the same search as in find_by_name and deleting the contact that matched the user's input (collected on choosing the "delete contact" option in the run method):

def delete_contact(name)
    delete = name.downcase
    contacts.each do |contact|
        if contact.full_name.downcase.include?(delete) 
            print "Delete #{contact.full_name}? (y/n) "
            input = gets.chomp
            case input
            when 'y'
                puts "Deleting #{contact.full_name}"
                contacts.delete(contact)
            else 
                break
            end
        end
    end
end

Then, any changes should be saved to the .yml file on exiting.