Problem with duplicated values in writing to an array

Hi,

The next code snippet:

arr = []
code = []

code[0] = ‘op1’
code[1] = ‘
code[2] = '

code[3] = 1

arr[0] = code
puts arr.inspect

code[0] = ‘op2’
code[3] = 2

arr[1]= code
puts arr.inspect

Produces the next result:

[[“op1”, “", "”, 1]]
[[“op2”, “", "”, 2], [“op2”, “", "”, 2]]

However, I expected :
[[“op1”, “", "”, 1]]
[[“op1”, “", "”, 1], [“op2”, “", "”, 2]]

What went wrong?

Thanks in advance,

Thiel C.

Hi,

Variables are references in Ruby. When you assign the “code” array to
the “arr” array, then “arr” will contain this exact array. Not some kind
of “snapshot” of the “code” array at this point of time.

So what you’re actually doing is you assign the same array (referenced
by “code”) to the first and second index of “arr”. If you want to have
two independent arrays, you have to clone “code” first.

Hi Jan,

Many thanks for your answer.

For me it was a very frustating problem. I should reread the
“Programming Ruby” and “The Well-Grounded Rubist” books.:wink:

Anyhow, I solved the problem by refactoring the code.

I have introduced a Code class for the code-array and now I can put the
code objects in the arr-array.

Greetings,

Thiel

Op 30-5-2012 15:44, Jan E. schreef:

Thiel C. wrote in post #1062600:

Anyhow, I solved the problem by refactoring the code.

I have introduced a Code class for the code-array and now I can put the
code objects in the arr-array.

This is certainly a good idea. Whenever you have multiple arrays with
the same specific structure, you should use an object/Struct instead.

However, you could solve the original problem simply by duplicating the
array:

#---------------

this doesn’t work:

container = []
a = [1, 2]
container << a
a[0] = 10
container << a
p container

this does:

container = []
a = [1, 2]
container << a
b = a.dup
b[0] = 10
container << b
p container
#---------------