Bug #6580
closedAssigning a value to a single element in an array that is contained in an array of arrays, updates the element in that position in all of the contained arrays
Description
=begin
Came across this bug the other day in both 1.8 and 1.9.3. It seems like it would have been discovered before, but I can't find anywhere that it has been reported.
Basically, when you have an array of arrays, and you attempt to assign a value to a single element of one of those arrays, it assigns the value to that element in all of the arrays.
Example:
(({arr = Array.new(5, Array.new(5))}))
[
[nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil]
]
(({arr[0][0] = 3}))
[
[3, nil, nil, nil, nil],
[3, nil, nil, nil, nil],
[3, nil, nil, nil, nil],
[3, nil, nil, nil, nil],
[3, nil, nil, nil, nil],
]
(({arr[2][3] = "test"}))
[
[3, nil, nil, "test", nil],
[3, nil, nil, "test", nil],
[3, nil, nil, "test", nil],
[3, nil, nil, "test", nil],
[3, nil, nil, "test", nil],
]
=end
Updated by jeremyevans0 (Jeremy Evans) over 13 years ago
This isn't a bug. You are creating an array where all five elements are the same array object. You probably want to do:
arr = Array.new(5){Array.new(5)}
That way each of the five elements in the outside array is a separate array.
Updated by nobu (Nobuyoshi Nakada) over 13 years ago
- Status changed from Open to Rejected