From: Paul Lutus Date: 2006-10-04T01:10:06+09:00 Subject: Re: sparse multi-dimensional arrays Bill Birkett wrote: > I did like to convert some programs I wrote in Perl to Ruby. I'm > working with sparse three dimensional data. Here's an example in > Perl. The array @a has just two elements. The rest are undefined. > > #!/usr/bin/perl -w > > $a[0][0][0] = 0; > $a[100][100][100] = 100; > > print "$a[0][0][0]\n"; > print "$a[100][100][100]\n"; > > The output: > > 0 > 100 > > Is there an easy way to implement this sort of data structure in > Ruby? The Array class seems limited to one dimension. I looked at the > Matrix class, but there doesn't appear to be any way of assigning > values to the individual matrix elements (which seems pretty strange, > so maybe I'm overlooking the obvious). The solution depends on what you are trying to accomplish. If your aim is to minimize storage space, then use a nested hash, with numeric indices as keys. If your aim is simply to create an n-dimensional array and you don't care about storage size, then follow the advice of another poster: #!/usr/bin/ruby -w dim_size = 100 arr = Array.new(dim_size) { Array.new(dim_size) { Array.new(dim_size,42) } } puts arr[39][56][24] 42 -- Paul Lutus http://www.arachnoid.com