Project

General

Profile

Actions

Bug #6580

closed

Assigning 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

Bug #6580: Assigning 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

Added by jmoline (James Moline) over 13 years ago. Updated over 13 years ago.

Status:
Rejected
Assignee:
-
Target version:
-
ruby -v:
ruby 1.9.3p0 (2011-10-30 revision 33570) [x86_64-darwin10.8.0]
Backport:
[ruby-core:45587]

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 Actions #1 [ruby-core:45588]

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 Actions #2 [ruby-core:45601]

  • Status changed from Open to Rejected
Actions

Also available in: PDF Atom