From: Jason Nordwick Date: 2006-10-04T02:17:46+09:00 Subject: Re: sparse multi-dimensional arrays Close: a={} a[[0,0,0]], a[[100,100,100]] = 0, 100 puts "#{a[[0,0,0]]}" puts "#{a[[100,100,100]]}" But you might like this better (my Ruby isn't very good, so please excuse me if I overcomplicate these definitions): class SparseMatrix < Hash alias :oldget :[] alias :oldset :[]= def[](*i); self.oldget(i); end def[]=(*i); v=i.pop; self.oldset(i,v); end end a = SparseMatrix.new a[0,0,0], a[100,100,100] = 0, 100 irb(main):017:0> a => {[0, 0, 0]=>0, [100, 100, 100]=>100} irb(main):018:0> puts "#{a[0,0,0]}" 0 => nil irb(main):019:0> puts "#{a[100,100,100]}" 100 => nil irb(main):020:0> puts "#{a[2,2,2]}" => nil irb(main):021:0> -j 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). > > -Bill