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 trialCarl Conroy
8,677 PointsGetting "NoMethod Error" even with code directly from Teacher's Notes.
My code is below. Can I get an extra set of eyes to see what might be wrong here? The program itself runs fine but it does not print out anything once the user states they do not want to add another. Instead, I get a NoMethod Error which is caused by the line
puts "Name: #{contact["name"]}"
The error reads "contact_list.rb:32:in block in <main>': undefined method
[]' for nil:NilClass (NoMethodError)
from contact_list.rb:31:in each'
from contact_list.rb:31:in
<main>' "
Any help is appreciated.
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 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())
answer = ask("Add another? y/n")
end
puts "---"
contact_list.each do |contact|
puts "Name: #{contact["name"]}"
if contact["phone_numbers"].size > 0
contact["phone_numbers"].each do |phone_number|
puts "Phone: #{phone_number}"
end
end
puts "----"
end
1 Answer
Jon Dalberg
6,788 PointsIn your "add_contact" method you need to return the "contact" object you have created. In Ruby the result of the last statement of a method will be the return value for that method unless you explicitly return something else. In your case, the last thing to happen is your "while" loop which returns "nil". Add a new line after your while loop and just put the "contact" variable there and it will not give you that error.
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
contact
end
Ahmed Mohamed Fouad
11,735 PointsAhmed Mohamed Fouad
11,735 Pointsthanks this solved my problem too