Strange behavior of Array

I want a multidimensional array with initial value 0, so I create it by

arr = Array.new(3, Array.new(3, 0)) => [[0, 0, 0], [0, 0, 0], [0,
0,
0]]

now I change the arr[0][0] to 1

arr[0][0] = 1
arr => [[1, 0, 0], [1, 0, 0], [1, 0, 0]]

It’s so strange for me, why it’s not [[1, 0, 0], [0, 0, 0], [0, 0, 0]]

In message
[email protected], “huang
zhimin” writes
:

I want a multidimensional array with initial value 0, so I create it by

arr = Array.new(3, Array.new(3, 0)) => [[0, 0, 0], [0, 0, 0], [0, 0,
0]]

You have now created an array consisting of three copies of the SAME
array [0,0,0].

This is a FAQ.

-s

Peter S. wrote:

This is a FAQ.

-s

Yeah, but at least give the guy a link to the correct solution, or
something.

This is how you do it:
arr = Array.new(3) { Array.new(3, 0) }

Dan

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs