Multi-dimensional (like 2) arrays in Ruby

Ut, oh… @matrix isn’t what I want?

ted@acacia:ruby > ruby Turning_Grille.rb
Enter the number of rows and the number of columns separated by a space.
2 3
Generating a 2-row by 3-column matrix containing 6 elements.

#<Turning_Grille:0x401ba144 @matrix=[[nil, nil, nil], [nil, nil, nil]], @cols=3, @rows=2>
ted@acacia:ruby >

···

doesn’t work or it appears to work, but it is not what you want.

YS.

“Ted” ted@datacomm.com writes:

Ut, oh… @matrix isn’t what I want?

ted@acacia:ruby > ruby Turning_Grille.rb
Enter the number of rows and the number of columns separated by a space.
2 3
Generating a 2-row by 3-column matrix containing 6 elements.

#<Turning_Grille:0x401ba144 @matrix=[[nil, nil, nil], [nil, nil, nil]], @cols=3, @rows=2>
ted@acacia:ruby >

doesn’t work or it appears to work, but it is not what you want.

try this:
matrix = Array.new(2, Array.new(3))
matrix[0][1] = 3
puts matrix[1][1] # => also 3!

and you wonder why.

In this case, Array.new(3) is evaluated first and produced an array
object. Then, Array.new(2, …) creates an array of two elements, each
element points to the same object created from Array.new(3).

So, it is equivalent to:
inner = Array.new(3)
matrix=Array.new(2, inner)

Now, are you sure you want to create a matrix where row 0 and row 1
points to the same column-set?

YS.