Christopher Phillips10,045 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.
Anthony MorenoiOS Development with Swift Techdegree Student 4,362 Points
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:
def one myvar = 1 puts myvar end def two myvar = 2 puts myvar end
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:
def make_burger contents = ["beef patty", "cheese"] add_ketchup(contents) p contents end def add_ketchup(my_array) my_array << "ketchup" end make_burger # prints: ["beef patty", "cheese", "ketchup"]