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

my code is perfect but it won't work?

def add_contact
  contact = {"name" => "", "phone_numbers" => []}
  contact["name"] = ask("What is the person's name?")
  answer = ""
  while answer != "n"
    answer = ask("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
end

answer = ""
while answer != "n"
  contact_list.push(add_contact())
end

I get an error saying that the variable "Contact_list is not defined?? help me!

Clayton Perszyk
Clayton Perszyk
Treehouse Moderator 48,850 Points

do you have a contact_list defined; I don't see it here.

Kris Blanchette
Kris Blanchette
174 Points

Can you show where you defined contact_list?

EDIT: didn't see Clayton's reply before asking.

1 Answer

Clayton Perszyk
MOD
Clayton Perszyk
Treehouse Moderator 48,850 Points

Nick,

I modified your code and was able to get it functioning

contact_list = [] # didn't see this defined

def add_contact
  contact = {"name" => "", "phone_numbers" => []}
  # ask() isn't a ruby method; so, unless you made one you need to use puts and gets.chomp
  puts "What is the person's name?" 
  contact["name"] = gets.chomp
  answer = ""
  while answer != "n"
    puts "Do you want to add a phone number? (y/n)"
    answer = gets.chomp
    if answer == "y"
      puts "Enter a phone number:"
      phone = gets.chomp
      contact["phone_numbers"].push(phone)
    end
  end
  # the contact needs to be returned, or nothing is given back to the calling code
  return contact
end

answer = ""
while true
 puts "would you like to add a contact? (y/n)"
 answer = gets.chomp
 # this will break out of the loop 
 if answer == 'n'
    break
  end
  contact_list.push(add_contact())
end

# output the results
puts contact_list

Best, Clayton

Clayton Perszyk
Clayton Perszyk
Treehouse Moderator 48,850 Points

I just watched the video and saw Jason created an ask() method, so if you use that, your code is fine; as long as you make the other changes. I think the main problems were that you weren't returning the contact and the missing contact_list.