# Using Array.new inside itself creates internal references?

**URL:** <https://forum.crystal-lang.org/t/using-array-new-inside-itself-creates-internal-references/948>\
**Category:** Help & Support\
**Created:** [July 12, 2019, 3:10am UTC](https://forum.crystal-lang.org/t/using-array-new-inside-itself-creates-internal-references/948 "2019-07-12T03:10:41Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![girng](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/girng/32/127_2.png) [@girng](https://forum.crystal-lang.org/u/girng)\
**Post date:** [July 12, 2019, 3:10am UTC](https://forum.crystal-lang.org/t/using-array-new-inside-itself-creates-internal-references/948/1 "2019-07-12T03:10:41Z")

</div>

Check this out, this is the weirdest thing ever. Playground: [https://play.crystal-lang.org/#/r/77qb/edit](https://play.crystal-lang.org/#/r/77qb/edit)

I did not want to use custom methods to create a Matrix because of `Array.new`. That’s why I tried to do it this way, but for some reason if you change one Array in the Matrix, all of those arrays get modified??

```auto
def create_matrix_for_inventory(r, h)
  temp = Array(Array(Int32)).new
  h.times do |i|
    temp << Array.new(r, 0)
  end
  temp
end

Inventory = Array.new(5, Array.new(7, 0))
#Inventory = create_matrix_for_inventory 4, 7

Inventory[1][2] = 44

pp Inventory

## WTF LOL??

```

---

<div class="post-metadata">

**Author:** ![watzon](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/watzon/32/481_2.png) [@watzon](https://forum.crystal-lang.org/u/watzon)\
**Post date:** [July 12, 2019, 3:46am UTC](https://forum.crystal-lang.org/t/using-array-new-inside-itself-creates-internal-references/948/2 "2019-07-12T03:46:37Z")

</div>

I’m fairly certain this is expected behavior. Array is a class, and therefore will be referenced. What you need to do is use a block to create a new array instance for each index. [https://play.crystal-lang.org/#/r/77qx](https://play.crystal-lang.org/#/r/77qx)

This happens because `Array.new` doesn’t call `dup` on the values you’re filling it with.

---

<div class="post-metadata">

**Author:** ![girng](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/girng/32/127_2.png) [@girng](https://forum.crystal-lang.org/u/girng)\
**Post date:** [July 12, 2019, 10:59am UTC](https://forum.crystal-lang.org/t/using-array-new-inside-itself-creates-internal-references/948/3 "2019-07-12T10:59:55Z")

</div>

Thank you, another class ref mistake by me, FFS.
