On Sun, Sep 6, 2009 at 10:11 PM, Mason K. [email protected]
wrote:
does not deliver the 5 that I would expect but instead, provides (in SciTE)
Thanks in advance!
Hi, Mason
In Ruby, Arrays are objects, they only have one dimension. But they can
hold
anything, including other arrays, so they can behave as multi
dimensional
arrays. To get your desired output, you would so something like this
#a two dimensional array
x = Array.new(3){ Array.new(3) }
p x # => [[nil, nil, nil], [nil, nil, nil], [nil, nil, nil]]
#a two dimensional array with your desired output
x = Array.new(3){|i| Array.new(3){|j| 3*i+j+1 } }
x # => [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
In this example, we say Array.new(3) which says to make an array with
three
indexes. Then we pass it a block, which determines how to initialize
each
index. The block accepts the variable i, which is the index being
assigned,
so it will have values 0, 1, and 2. Then for each of these indexes, we
want
it to be an Array, which gets us our second dimension. So in our block
we
assign another Array.new(3), to say an array with three indexes. We pass
this Array the block {|j| 3*i+j+1} so j will have values 0, 1, 2 and i
will
have values 0, 1, 2. Then we multiply i by 3, because each second
dimension
has three indexes, and we add 1 because we want to begin counting at 1
instead of zero.
So this says “create an array with three indexes, where each index is an
array with three indexes, whose values are 3 times the index of the 1st
dimension, plus the second dimension, plus 1”
Hope that helps.