I misunderstand Array behaviour
When i created this matrix
matrix, cell = [], []; 5.times { cell << [] } # columns
3.times { matrix << cell } # lines
matrix
sample_data = (0..5).to_a
matrix[1][2] = sample_data.clone
matrix.each { |line| puts "line : #{line}" }
I have this result
line : [[], [], [0, 1, 2, 3, 4, 5], [], []]
line : [[], [], [0, 1, 2, 3, 4, 5], [], []]
line : [[], [], [0, 1, 2, 3, 4, 5], [], []]
Instead the expected result
line : [[], [], [], [], []]
line : [[], [], [0, 1, 2, 3, 4, 5], [], []]
line : [[], [], [], [], []]
What wrong ?
The problem is with your line:
You are using the same object
cellas the three rows ofmatrix.The key is that
Arrayis a mutable object. Even if you modify it, its identity does not change. The three occurences ofcellare pointing to the same instance (object). If you access and modify it through one occurence of it, the other occurences will reflect that change.If you change this line to:
then you will get the desired result.