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 trialJiaying Wang
7,869 PointssimpleContact.rb:37:in `block in <main>': undefined method `each' for 21:Fixnum (NoMethodError)
I tried to run the code but encoutered the following error, i compared my code with teacher's note but still can't figure out the problem
simpleContact.rb:37:in block in <main>': undefined method
each' for 21:Fixnum (NoMethodError)
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's your name?")
answer = ""
while answer != "n"
puts "Do you want to add a phone number? y or n"
answer = gets.chomp
if answer == 'y'
contact["phone_numbers"] = ask("What's your phone number", "number")
end
end
return contact
end
contact_list = []
answer = ""
while answer != 'n'
contact_list.push(add_contact())
answer = ask("Ask for another one? y/n")
end
puts "--------"
contact_list.each do |contact|
puts "Name: #{contact["name"]}"
if contact["phone_numbers"].size > 0
contact["phone_numbers"].each do |number|
puts "Phone: #{number}"
end
end
puts "--------\n"
end
1 Answer
dxt
16,505 PointsNot sure if it's the issue, but I noticed you have an array of phone numbers in your contact hash. Look in your while loop of the add_contact method:
contact["phone_numbers"] = ask("What's your phone number", "number")
It would make more sense to push the items to an array rather than setting that array as a phone number:
contact["phone_numbers"].push(ask("What's your phone number", "number"))
I hope it fixes your issue.
Jiaying Wang
7,869 PointsJiaying Wang
7,869 PointsThanks, I figured it out earlier today, phone_numbers is an array inside of a hash, so I should use push instead of calling ask method to add value into it.