On 17/08/05, Bill Kelly <billk / cts.com> wrote: > From: "Xeno Campanoli" <xeno / eskimo.com> > > > > There are just too many problems that can quickly be solved by > > multi-dimensional arrays and hashes not to have them and have them > > easily. I used the hack from "matz" today to make a 2d hash, and it's > > ugly and unworthy of Ruby. You should be able to do this without any > > extra steps just like in Perl. If the project ends up getting bigger > > THEN you refactor it, but YOU JUST GOT TO HAVE THAT. > > I don't know how to do it with Array, because Array doesn't > seem to accept a block for its default value generation like > Hash does. > > But with Hash: > > hoh = lambda { Hash.new {|h,k| h[k] = hoh.call} } > > >> x = hoh.call # create autovivifying hash-of-hashes > => {} > >> x[1][2][3][4][5] = "spleen" > => "spleen" > >> x > => {1=>{2=>{3=>{4=>{5=>"spleen"}}}}} > > > Regards, > > Bill Though I never had use for this, here is my attempt on an autovivifying array of arrays: class Autoarray < Array def initialize(size=0, default=nil, update = nil, update_index = nil) super(size, default) @update, @update_index = update, update_index end def [](k) if k.abs() < self.length super(k) else Autoarray.new(0, nil, self, k) end end def []=(k, v) @update[@update_index] = self if @update and @update_index super end end a = Autoarray.new a[1][2][3] = 12 a #=> [nil, [nil, nil, [nil, nil, nil, 12]]] a[2][3][4] #=> [] a #=> [nil, [nil, nil, [nil, nil, nil, 12]]] regards, Brian -- http://ruby.brian-schroeder.de/ Stringed instrument chords: http://chordlist.brian-schroeder.de/