Jeff Schwab
8/16/2006 12:48:00 PM
marinho.tobolla@syncity.de wrote:
> Well am I right, that in Ruby there are only one dimensional arrays, and that i have to add an array into an array to get multidimensional arrays, or is there a simpler more ruby like way to create them ?
That's technically true, but it doesn't usually matter. In C, you're
declaring how much space you'll need to store data, but you don't have
to do that in Ruby. Ruby arrays will grow as necessary. If you just
want a 2d array, the simplest way is to create one and add to it as
necessary.
In the trivial case, you can do something like:
a = [[]]
a[0] << "hello" # Add a column to the first row.
a << ["world"] # Add a row.
Or you can initialize the size with:
a = [[0] * 6] * 4 # warning: sizes are (col,row), indices are (row,col)
The biggest problem is that you get a bunch of references to the same
object, so if you modify it, you mess up a whole column. For example:
a[3][5] = 15
Produces:
[[0, 0, 0, 0, 0, 15]
[0, 0, 0, 0, 0, 15]
[0, 0, 0, 0, 0, 15]
[0, 0, 0, 0, 0, 15]]
If you start using more dimensions, the row/column metaphor can break
down, so indexing can become a little confusing; you pretty much have to
start thinking of indices as (z,y,x) in some space.
Here's my philosophical take on this: Multi-dimensional rows generally
represent tables of data. Storing data in tables is a nice way to make
it accessible from procedural code, but is dead-set against the
object-oriented paradigm. If you're programming in Ruby, and you find
yourself with a multi-dimensional array, what you really want is a
single-dimensional array of objects, each of which represents a record.
If you're sure you want a multi-dimensional array, then you probably
are doing some kind of numeric computation, and frankly, you might be
happier implementing it in C or C++.