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 Ruby Loops Build a Simple Contact List Part 2: Adding Contacts

Code not running cant quit program

Not sure why this wont work. It asks me for the name but after i enter it doesnt do anything else even if i press n. Does not ask for the phone number at all

def ask(question, kind="string")
  print question + " "
  answer = gets.chomp
  answer = answer.to_i if kind == "number"
  return answer
end

def add_contact
  contact = {"name" =>"","phone_numbers" => []}
  contact["name"] = ask("What is the person's name?")
  answer = ""
  while answer != "n"
    answer = "Do you want to add a phone number? (y/n) "
    if answer == "y"
      phone = ask("Enter a phone number:")
      contact["phone_numbers"].push(phone)
    end
  end
  return contact
end

contact_list = []

answer = ""
while answer != "n"
  contact_list.push(add_contact())
  answer = ask("Add another? (y/n)")
end  

Your first problem lies in the fact that you forgot the "do" keyword in both while-statements. Secondly, you do not actually print "Do you want to add a phone number? (y/n)" in the add_contact method. When you print this, you also want to allow your program to catch input with "answer = gets.chomp". The following code is a working solution of your example:

def ask(question, kind = 'string')
  print question + ' '
  answer = gets.chomp
  answer = answer.to_i if kind == 'number'
  return answer
end

def add_contact
  contact = {'name' => '', 'phone_numbers' => []}
  contact['name'] = ask("What is the person's name?")
  answer = ''
  while answer != 'n' do
    print 'Do you want to add a phone number? (y/n) '
    answer = gets.chomp
    if answer == 'y'
      phone = ask('Enter a phone number: ')
      contact['phone_numbers'].push(phone)
    end
  end
  return contact
end

contact_list = []
answer = ''
while answer != 'n' do
  contact_list.push(add_contact())
  answer = ask('Add another? (y/n) ')
end