Array overwrite question

It is about array question
below is my program:

aa = [2,3,4,5,6,7,8]
bb = [22,3,66,66,66,66]
cc = bb

n = 0
while aa[n]!=nil

m = 0
while bb[m]!= nil

if (aa[n]== bb[m])

  cc[m] = 99
end
m+=1

end
n+=1
end

output results:
bb is [22,99,66,66,66,66]
cc is [22,99,66,66,66,66]

why bb array will be overwrite??

I want its output:
bb is [22,3,66,66,66,66]
cc is [22,99,66,66,66,66]

Thanks,

bb and cc are a same object, you change cc, bb will also be changed.

you should modify the 3rd line to:

cc = bb.dup

Joey Z. wrote in post #1010405:

bb and cc are a same object, you change cc, bb will also be changed.

you should modify the 3rd line to:

cc = bb.dup

If on multi-dimension array?

I try .dup it cant work!!

Thanks,

CC Chen wrote in post #1010408:

If on multi-dimension array?

I try .dup it cant work!!

what version of ruby are you using, with both 1.8.7 and 1.9.2
Array#dup works for me…

bb = [[1,2], [3,4], [5,6]]
cc = bb.dup

p cc

=> [[1, 2], [3, 4], [5, 6]]

changing your code as Joey suggested gives me the output you were
looking for:

[22, 3, 66, 66, 66, 66]
[22, 99, 66, 66, 66, 66]

  • j

jake kaiden wrote in post #1010461:

CC Chen wrote in post #1010408:

If on multi-dimension array?

I try .dup it cant work!!

what version of ruby are you using, with both 1.8.7 and 1.9.2
Array#dup works for me…

bb = [[1,2], [3,4], [5,6]]
cc = bb.dup

p cc

But of course, the subarrays in cc and the subarrays in bb are the same
objects.

bb = [[1,2], [3,4], [5,6]]
cc = bb.dup
bb[0] << 3
p cc

[[1, 2, 3], [3, 4], [5, 6]]

You can do the dups for the second level too yourself, or use this deep
copy trick:

cc = Marshal.load(Marshal.dump(bb))

CC Chen wrote in post #1010408:

Joey Z. wrote in post #1010405:

bb and cc are a same object, you change cc, bb will also be changed.

you should modify the 3rd line to:

cc = bb.dup

If on multi-dimension array?

I try .dup it cant work!!

Thanks,

aa2 = [[2,3],[4,5],[6,7]]
bb2 = [[11,22],[33,44],[6,7]]
cc2 = aa2.dup

i = 0
while i< 3

j = 0
while j < 2

if (aa2[i][j]== bb2[i][j])

  cc2[i][j] = 88

end
j+=1

end
i+=1
end

print aa2,"\n"
print bb2,"\n"
print cc2

The output are:
aa2 = [[2,3],[4,5],[88,88]]
bb2 = [[11,22],[33,44],[6,7]]
cc2 = [[2,3],[4,5],[88,88]]

I want its output:
aa2 = [[2,3],[4,5],[6,7]]
bb2 = [[11,22],[33,44],[6,7]]
cc2 = [[2,3],[4,5],[88,88]]

The .dup seems just can work on one dimension array.
How to solve the problems on multi-dimension array?

Thanks,

like Brian says:

cc2 = Marshal.load(Marshal.dump(aa2))

Hans M. wrote in post #1010878:

like Brian says:

cc2 = Marshal.load(Marshal.dump(aa2))

In this particular case #map also works because we know the depth to be
two levels:

arr = [[1,2], [3,4], [5,6]]
copy = arr.map {|a| a.dup}

Cheers

robert