From: Logan Capaldo Date: 2006-10-03T23:11:49+09:00 Subject: Re: sparse multi-dimensional arrays On Tue, Oct 03, 2006 at 10:58:22PM +0900, 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). > It's pretty easy if you know the dimensions before hand, a bit more hackery pokery if you don't. a = Array.new(101) { Array.new(101) { Array.new(101) } } a[0][0][0] = 0 a[100][100][100] = 100 puts a[0][0][0] puts a[100][100][100]