Using Array.new inside itself creates internal references?

Check this out, this is the weirdest thing ever. Playground: 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??

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

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

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

1 Like

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