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 trialJoshua Goss
5,714 PointsNot sure how the 'push' method could be undefined on line 18
contact_list = []
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 = ask ("Do you want to leave a phone number")
if answer == "y"
phone = ask ("Enter a phone number.")
contact ["phone_numbers".push(phone)]
end
end
return contact
end
answer = ""
while answer != "n"
contact_list.push (add_contact())
answer = ask("Add another?")
end
puts contact_list
output:
What is the person's name? J
Do you want to leave a phone number y
Enter a phone number. 123
Traceback (most recent call last):
1: from contact_list.rb:27:in `<main>'
contact_list.rb:18:in `add_contact': undefined method `push' for "phone_numbers":String (NoMethodError)
treehouse:~/workspace$ ruby contact_list.rb
Error:
Traceback (most recent call last):
1: from contact_list.rb:27:in `<main>'
contact_list.rb:18:in `add_contact': undefined method `push' for "phone_numbers":String (NoMethodError)
2 Answers
Jeff Muday
Treehouse Moderator 28,722 PointsNice job coming up with the code. You almost got it!
Change the slight error when you are "pushing" phone
into the phone_number
array. See below.
contact_list = []
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 = ask ("Do you want to leave a phone number")
if answer == "y"
phone = ask ("Enter a phone number.")
# contact ["phone_numbers".push(phone)]
contact["phone_numbers"].push(phone)
end
end
return contact
end
answer = ""
while answer != "n"
contact_list.push (add_contact())
answer = ask("Add another?")
end
puts contact_list
Joshua Goss
5,714 PointsI see! "Push" is not something that works because the push method cannot be used on a string so the declaration of the array ends at the String. Thank you Jeff :)