I am facing something i do not fully understand.
I have an array whose elements are arrays.
So I have two nested loops, in the inner loop I fill my inner array then in the outer loop i fill the outer array with the inner array.
arr=[]
mat=[]
for m in (0..1)
for k in (0..1)
arr[k]=rand.to_s
end
mat[m]=arr
end
At the end my matrix is filled with two array; each array contains the values calculated in the last iteration. If i want the first element in matrix to contain the first computed array I have to reinitialize the arr object at each loop. So it seems that assignment is made by reference until the arr object is "cleaned". If I add
mat[m]=arr
arr=[]
all works as expected: mat[0] will contain the array computed in the first loop, and mat[1] will contain the array computed in the second loop.
Is this by design or is it an undesired side effect? This is happening only if I assign arrays as array elements. If if fill an array with simple string variables in a loop all goes as expected.
I know that it is good programming practice to avoid reusing objects, but this behavior is anyway strange.