On 17/08/05, Pit Capitain <pit / capitain.de> wrote:
> Brian Schr?der schrieb:
> > Though I never had use for this, here is my attempt on an
> > autovivifying array of arrays:
> >
> >  [snip old code]
>
> Very nice. There are problems with negative indexes (try a[1][-2][2])
> but I'm sure they can be fixed. I really like the idea.
> 
> Regards,
> Pit
> 
> 

Should have written unit tests, but it is just a hack. Heres the
correction, so no correctness guarantee yet.

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 -self.length+1 < k and k < 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]]]
a[1][-2][1] = "Negative"
a             #=> [nil, [nil, [nil, "Negative"], [nil, nil, nil, 12]]]

regards,

Brian

-- 
http://ruby.brian-schroeder.de/

Stringed instrument chords: http://chordlist.brian-schroeder.de/