Reputation: 96454
I tried:
1.9.3-p448 :046 > a=Array.new(7){Array.new(7)}
=> [[nil, nil, nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil, nil, nil]]
1.9.3-p448 :047 > a[0,0]='a'
=> "a"
1.9.3-p448 :048 > a[0,1]='b'
=> "b"
1.9.3-p448 :049 > a[0,2]='c'
=> "c"
1.9.3-p448 :050 > a[1,0]='d'
=> "d"
1.9.3-p448 :051 > a[1,1]='e'
=> "e"
1.9.3-p448 :052 > a[1,2]='f'
=> "f"
and I got:
1.9.3-p448 :053 > a
=> ["c", "f", [nil, nil, nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil, nil, nil]]
but I wanted
1.9.3-p448 :053 > a
=> ["a","b","c",nil,nil,nil], ["d","e","f", nil, nil, nil, nil],
[nil, nil, nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil, nil, nil],
[nil, nil, nil, nil, nil, nil, nil]]
Upvotes: 0
Views: 796
Reputation: 58224
In Ruby, as @Daniel points out, accessing multidimensional array elements is done as it is done in, for example, C.
The notation you're attempting to use is from, for example, Pascal, but doesn't work the way you think it does in Ruby. What it does in Ruby is give a start index and a count.
So if you have:
a = ['a','b','c','d','e','f']
Then a[2,3]
will be:
['c','d','e']
This is described in the Ruby Array class documentation. If you attempt to assign to it, Ruby will dynamically change the array accordingly. In the above example, if I do this:
a[2,3] = 'h'
Then a
will become:
['a','b','h','f']
Or if I do this:
a[2,0] = 'j'
Ruby inserts a value at position 2 and now I get:
['a','b','j','h','f']
In other words, assigning a value to a[2,3]
replaced the subarray of three values with whatever I assigned to it. In the case of a two-dimensional array, such as in the original example,
a[0,0] = 'a' # Inserts a new first row of array with value 'a'
a[0,1] = 'b' # Replaces the entire first row of array with 'b'
a[0,2] = 'c' # Replaces the entire first two rows of array with 'c'
a[1,0] = 'd' # Inserts a new first row of array with value 'd'
a[1,1] = 'e' # Replaces the entire second row of array with 'e'
a[1,2] = 'f' # Replaces the entire second and third rows of array with 'f'
Thus, you get the result that you see.
Upvotes: 5
Reputation: 10235
You're currently assigning letters to a range of the outer array. This is the syntax to reference the inner arrays:
a[0][0]='a'
Upvotes: 4