2

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?

2
  • Read stackoverflow.com/questions/1720932/… Commented Apr 2, 2013 at 21:26
  • 1
    Not directly relevant to your problem, but take a look at narray for multi-dimensional numerical arrays. Commented Apr 2, 2013 at 22:03

1 Answer 1

5

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) }
Sign up to request clarification or add additional context in comments.

2 Comments

Note you could use the block form of Array::new to get distinct row objects as well. @board = Array.new(10) { Array.new(10) }
Thanks for the tip. That looks a lot cleaner than using map.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.