Project

General

Profile

Bug #13797

Using .push on an 2d array class-instance variable causes the whole array to be overwritten with the .push value; is this a bug?

Added by gggfx (James Pike) about 3 years ago. Updated about 3 years ago.

Status:
Rejected
Priority:
Normal
Assignee:
-
Target version:
-
ruby -v:
ruby 2.2.6p396 (2016-11-15 revision 56800) [x64-mingw32]
[ruby-core:82326]

Description

I was building a class to hold results for analysis 'cells' in a model; each 'cell' is a position in an array, with each result stored in a sub-array - this collates multiple results per cell which can then be iterated through later for model interactions.

I created this as a class (my data is addressed by time,x,y and z coordinates; my class writers and readers convert t-x-y-z into a position on a 1d array, this is faster than named instance variables).

When it comes to pushing the data into the instance array variable it causes all the slots of the array to be pushed with the value.

This is my first bug report and I'm newish to Ruby so I apologise if I've missed any key information. I attach code with a test-example I wrote which demonstrates the behaviour in question.

NORMAL CASE

testArray = [[],[],[],[],[]]
testArrayShouldLookLike = [[result1],[],[],[],[]]
testArrayCanThenLookLike = [[result1, result2],[],[],[],[]]  etc.

CLASS CASE

def write(position, data)
    @testArray[position].push(data)
end

testArrayComesOutAs = [[result1],[result1],[result1],[result1],[result1]]

Files

Class bug_JP.rb (1.13 KB) Class bug_JP.rb Test code showing normal and class cases gggfx (James Pike), 08/10/2017 11:22 AM

Updated by nobu (Nobuyoshi Nakada) about 3 years ago

  • Status changed from Open to Rejected
  • Description updated (diff)

You share the same array instance as sub-arrays.

                def initialize(totalSize)
                        @data_array = Array.new(totalSize,[])   
                end

Make different instances.

@data_array = Array.new(totalSize) {[]}

or

@data_array = [[]] * totalSize

Updated by nobu (Nobuyoshi Nakada) about 3 years ago

nobu (Nobuyoshi Nakada) wrote:

@data_array = [[]] * totalSize

Sorry, this doesn't fix it. Use Array.new with a block.

Also available in: Atom PDF