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 trialNick Yates
8,621 Pointsmy 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!
Kris Blanchette
174 PointsCan you show where you defined contact_list?
EDIT: didn't see Clayton's reply before asking.
1 Answer
Clayton Perszyk
Treehouse Moderator 48,850 PointsNick,
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
Treehouse Moderator 48,850 PointsI 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.
Clayton Perszyk
Treehouse Moderator 48,850 PointsClayton Perszyk
Treehouse Moderator 48,850 Pointsdo you have a contact_list defined; I don't see it here.