ruby - Why doesn't this methods allow me to add to an array? -


i don't understand why code below doesn't work me out? trying create method adds items end of array. think problem lies within last line of code trying access local variable... thanks!

def add_to_array(name)   array = []   array << name end  add_to_array("rob") add_to_array("jack")  p array 

the problem you're creating new array every time call add_to_array method.
besides that, array local variable , has scope limited add_to_array lifetime.

try following:

def add_to_array(array, name)   array << name end  array = [] add_to_array(array, "rob") add_to_array(array, "jack") p array 

Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -