Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

Sean Flanagan
Sean Flanagan
33,235 Points

Deleting a contact


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")

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}"

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