Bug #12765
closedAn [element] multiply an number, every element in the list would be modified after modifying only one of then.
Description
element = [1] list = [element.clone] * 3 p list #[[1], [1], [1]] list[0][0] = -1 # should be [[-1], [1], [1]] p list # [[-1], [-1], [-1]]
The list initialized as [ [1], [1] ]. Then we assign the list[0][0], which is 1, as -1, and the list[1][0] is changed as -1 too.
Updated by Hanmac (Hans Mackowiak) over 7 years ago
this is not much of a bug,
your array has three times the same element object (same object id)
you want:
list = Array.new(3) { [1] } #=> [[1], [1], [1]]
list[0][0] = -1
list #=> [[-1], [1], [1]]
Updated by fanjieqi (jieqi fan) over 7 years ago
element = [1] list = Array.new(3) { element } p list #[[1], [1], [1]] list[0][0] = -1 # should be [[-1], [1], [1]] p list # [[-1], [-1], [-1]]
OK, and could you please figure out this one?
Updated by marcandre (Marc-Andre Lafortune) over 7 years ago
- Status changed from Open to Rejected
Clearly not a bug.
list[0][0] = -1 # => same as doing:
element[0] = -1
For further questions, please use general ruby mailing list or StackOverflow, thanks.