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 trial
Christopher Phillips10,061 Points
How would I do this:
Suppose I have 2 methods. The first method is like this video. It creates a hash with name and then items which are stored in an array.
How would I add items to that array from inside another, separate method? I'm getting the undefined local variable or method error because I don't think I can access the array inside a different method.
Can you type an example of how you’re trying to add to the array in method 1 from method 2?
Jay McGavrenTreehouse Teacher
This is an issue with variable scoping. Suppose you have two different methods:
myvar = 1
myvar = 2
The above code contains two completely separate variables, both of which happen to be named
myvar. They are local variables, meaning they are can only be read or modified inside the method where they are declared. This is a good thing; if both methods ran at the same time (which could happen using threads), you wouldn't want one method changing the other method's value for
If you want to update a local variable using a different method, you'll need to pass it to the other method as an argument, like this:
contents = ["beef patty", "cheese"]
my_array << "ketchup"
make_burger # prints: ["beef patty", "cheese", "ketchup"]