0

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 ?

2 Answers 2

6

The problem is with your line:

3.times { matrix << cell }

You are using the same object cell as the three rows of matrix.

The key is that Array is a mutable object. Even if you modify it, its identity does not change. The three occurences of cell are 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:

3.times { matrix << cell.dup } 

then you will get the desired result.

Sign up to request clarification or add additional context in comments.

1 Comment

Or since cell is empty just use a new [] instead of specifying cell... 3.times { matrix << [] }
2

You're putting the same object (cell) into the matrix three times.

this will fix your bug:

3.times { matrix << cell.clone } # lines

...but you might want to explain what problem you're trying to solve with this code, as there may be better ways...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.