From: mark sparshatt Date: 2004-09-17T05:32:32+09:00 Subject: Re: 2-d arrays Barry Sperling wrote: > > Reading the recent posts about ant-wars, I thought that, as a > nuby, it would be interesting to try to recreate the ant-wars engine. > I looked at their code a little, and then started in. I appreciate > that James Edward Gray II provided us with his code, but I'll look at > it after I've made more progress. > I decided to create 2-d arrays to hold the data for given > positions ( hexagonal blocks ). One would hold the amount of food at > a position, another would hold the traversability of it, etc. My > first attempt failed in a strange way and the point of this email is: > why? > > Method 1 > > cols = 10 > empty_row_int = Array.new( cols, 0 ) this creates an array > $food_layout = Array.new > rows.times { $food_layout.push( empty_row_int ) } this pushes that array into $food_layout rows times. > puts $food_layout[ 0 ][ 0 ] # 0 > $food_layout[ 0 ][ 0 ] = 6 # SET FOOD ITEMS IN HEXAGON > puts $food_layout[ 0 ][ 0 ] # 6 > puts $food_layout[ 1 ][ 0 ] # 6 WRONG! > $food_layout[0] and $food_layout[1] both refer to the same array object (empty_row_int) so they both hold the same values. The correct way to do this would be cols = 10 $food_layout = Array.new rows.times { $food_layout.push( Array.new( cols, 0 ) ) } puts $food_layout[ 0 ][ 0 ] # 0 $food_layout[ 0 ][ 0 ] = 6 # SET FOOD ITEMS IN HEXAGON HTH -- Mark Sparshatt