From: Robert Klemme Date: 2005-08-17T19:11:15+09:00 Subject: Extend Class Matrix? (was: Re: Ruby 2 Idea: You've got to have a[a][b][c][d][e][f][g][h][i]...) Pit Capitain wrote: > Brian Schr�der schrieb: >> 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]]] > > 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. While reading this thread I thought class Matrix would be a good solution, but it lacks these properties: - factory method that takes dimension sizes instead of actual elements - capability to handle more than two dimensions - autovivification How do people think about extending class Matrix of the std lib with these properties? We could then have Matrix[3,4,5,10,2] which creates a five dimensional 3x4x5x10x2 Matrix etc. Note that this factory method does not conflict with the old usage Matrix[[1,2],[3,4]] where arrays were used to provide actual values. Kind regards robert