# Strange behavior of Array

**URL:** <https://www.ruby-forum.com/t/strange-behavior-of-array/106416>\
**Category:** Ruby\
**Created:** [June 10, 2007, 5:14am UTC](https://www.ruby-forum.com/t/strange-behavior-of-array/106416 "2007-06-10T05:14:30Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![huang\_zhimin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/54ee81/32.png) [@huang\_zhimin](https://www.ruby-forum.com/u/huang_zhimin)\
**Post date:** [June 10, 2007, 5:14am UTC](https://www.ruby-forum.com/t/strange-behavior-of-array/106416/1 "2007-06-10T05:14:30Z")

</div>

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]]

---

<div class="post-metadata">

**Author:** ![huang\_zhimin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/54ee81/32.png) [@huang\_zhimin](https://www.ruby-forum.com/u/huang_zhimin)\
**Post date:** [June 10, 2007, 5:18am UTC](https://www.ruby-forum.com/t/strange-behavior-of-array/106416/2 "2007-06-10T05:18:30Z")

</div>

In message  
[removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid), “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

---

<div class="post-metadata">

**Author:** ![huang\_zhimin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/54ee81/32.png) [@huang\_zhimin](https://www.ruby-forum.com/u/huang_zhimin)\
**Post date:** [June 10, 2007, 5:28am UTC](https://www.ruby-forum.com/t/strange-behavior-of-array/106416/3 "2007-06-10T05:28:31Z")

</div>

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
