2

I created a 2-D array and tried to copy its value. I tried assignment, dup, and clone.

@grid = Array.new(3) { Array.new(3) }
new_grid = @grid.clone

Whenever I try to change a value in the new variable, the change is reflected in the original array.

new_grid[0][0] = true
@grid # => [[true, nil, nil], [nil, nil, nil], [nil, nil, nil]]

Is there any way to avoid this linking of values?

sawa
  • 165,429
  • 45
  • 277
  • 381
frugalcoder
  • 959
  • 2
  • 11
  • 23

1 Answers1

2

Yes. Do deep dup or clone.

new_grid = @grid.map(&:dup)
sawa
  • 165,429
  • 45
  • 277
  • 381