fbonetti
fbonetti

Reputation: 6672

Setting the value of an element within a nested array

I'm trying to create a simple 10x10 Array so that I can create Conway's Game of Life, but I'm running into some strange behavior. First I initialize the board:

@board = Array.new(10, Array.new(10))
(0..9).each do |row|
    (0..9).each do |column|
        @board[row][column] = rand(0..1)
    end
end

Which produces this:

1000000111
1000000111
1000000111
1000000111
1000000111
1000000111
1000000111
1000000111
1000000111
1000000111
1000000111

Looks fishy but it's entirely possible that this could be generated randomly. The real problems start when I try to set the value of an individual cell. When I change the value, it sets the entire column to that value! For example, let's say I change the value of the first cell:

@board[0][0] = 0

What I get is:

0000000111
0000000111
0000000111
0000000111
0000000111
0000000111
0000000111
0000000111
0000000111
0000000111
0000000111

What gives? Why does the value change for ALL cells in column 0 instead of just the cell at 0, 0?

Upvotes: 2

Views: 632

Answers (1)

fbonetti
fbonetti

Reputation: 6672

I figured it out. When I initialized @board with Array.new(10, Array.new(10)), it created an Array of 10 identical Arrays. That is, each Array had the same object_id.

@board[0].object_id
=> 22148328
@board[1].object_id
=> 22148328

I solved the issue by using the map method:

@board = Array.new(10).map{ |x| Array.new(10) }

Upvotes: 5

Related Questions