I suspect method 1 doesn't do what you expect because you create one
single row and then make an array in which every element is that same
row. Try instead:
Method 1'
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
puts $food_layout[ 0 ][ 0 ] # 6
puts $food_layout[ 1 ][ 0 ] # 0
-- MarkusQ
On Thu, 2004-09-16 at 13:09, 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 )
> $food_layout = Array.new
> rows.times { $food_layout.push( empty_row_int ) }
> 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!
>
> Then I read some archived emails from the group and found Matrix
> mentioned, but a matrix couldn't be changed by assignment. However, it
> COULD be converted into an array, and so we get:
>
> Method 2
>
> require 'matrix'
> maf = Matrix.zero( 10 ) # A SQUARE MATRIX, 10X10, INITIALIZED TO 0
> $food2_layout = maf.to_a # MATRIX TO ARRAY
> puts $food2_layout[ 0 ][ 0 ] # 0
> $food2_layout[ 0 ][ 0 ] = 6 # SET FOOD ITEMS IN HEX
> puts $food2_layout[ 0 ][ 0 ] # 6
> puts $food2_layout[ 1 ][ 0 ] # 0
>
> Then I found another method was mentioned as listed in The Ruby Way:
>
> Method 3
>
> matrix = ( 0..9 ).map { ( 0..9 ).map { 0 } }
>
> and when I use puts with the code as above, it works.
> I understand Method 2, I "sort of" understand Method 3, but I don't know
> why "my" Method 1 doesn't work.
> Thanks,
> Barry
>
>