[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Multidimensional Arrays

Tim Pease

11/15/2006 9:14:00 PM

On 11/15/06, Smgspices@aol.com <Smgspices@aol.com> wrote:
>
> I thought the answer about how to create multidimensional arrays as
> presented here was very interesting, "create an array of arrays." A funny
> thing happened on the way to the store.
> I fired up FreeRIDE and entered, "chessboard = Array.new(8, Array.new(8, "
> ")) like so:
>
> irb(main):009:0> chessboard=Array.new(8,Array.new(8," "))
> => [[" ", " ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ",
> " ", " "], [" ", " ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", "
> ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " ", " "], [" ", " ", " ",
> " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " ", " "], [" ", "
> ", " ", " ", " ", " ", " ", " "]]
>
> This was exactly as I expected. Then I tried putting a pawn on the board:
>
> irb(main):010:0> chessboard[3][3]="Pawn"
> => "Pawn"
>
> Then I looked at the board:
>
> irb(main):011:0> chessboard
> => [[" ", " ", " ", "Pawn", " ", " ", " ", " "], [" ", " ", " ", "Pawn", "
> ", " ", " ", " "], [" ", " ", " ", "Pawn", " ", " ", " ", " "], [" ", " ", "
> ", "Pawn", " ", " ", " ", " "], [" ", " ", " ", "Pawn", " ", " ", " ", " "],
> [" ", " ", " ", "Pawn", " ", " ", " ", " "], [" ", " ", " ", "Pawn", " ", "
> ", " ", " "], [" ", " ", " ", "Pawn", " ", " ", " ", " "]]
>

Array.new( size, obj )

This will create an array of _size_ with the same _obj_ in every
position of the array. So you line above

chessboard=Array.new(8,Array.new(8," "))

created a new chessboard with the same array (the rows) copied eight
times into the array. You can see this by doing ...

chessboard.each {|row| puts row.object_id}

You will see that the object_id of each row is the same -- hency they
are the same object -- hency you see the pawn at position 3 of each
row.

Try this one ...

chessboard = Array.new(8) {|idx| Array.new(8, "")}
chessboard[3][3] = "pawn"

This will do what you expect. Read the documentation for Array.new It
will explain all these subtle nuances.

Blessings,
TwP