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 trialchristine picone
4,510 PointsRuby loops contact list challenge
Here is the prompt: Using the each method, iterate over the contact_list array. Assign each array item to the local variable contact in the block and print out the value of the name and phone_number keys.
Here is the code:
contact_list = [
{"name" => "Jason", "phone_number" => "123"},
{"name" => "Nick", "phone_number" => "456"}
]
name = ""
phone_number = ""
contact_list.each do |item|
contact = item
print "#{name} #{phone_number}"
end
I am wondering why we need to add the name = "" and phone_number = "" in the code above. Without it, you get " undefined local variable or method 'name' " . Can anyone explain why we have to make variables out of name and phone_number? Thanks.
2 Answers
Carl Reyes
Courses Plus Student 7,225 PointsHonestly, you just have to initialize variables, and there's not really a way around it.
The problem in this specific example has to do with scope. The "name" and "phone_number" variables only exist inside of the contact_list, not the global space. Initializing them as blank gives the loop a place to put the names (in memory) so you can ask for them later.
christine picone
4,510 PointsOkay, thanks Carl. I guess as a novice I wasn't thinking of them as variables at all, just as keys and values.
Thanks again, Christine
Carl Reyes
Courses Plus Student 7,225 PointsYeah it can be confusing. You just have to think of WHERE the values are stored and where you need to be able to access them from. Hope this helped!