From: Marnen Laibow-Koser Date: 2009-11-19T23:49:07+09:00 Subject: Re: dynamic array? Freak Guard wrote: > I'd like to store 2d-data into an dynamic Array. The Matrix class got > the problem of being static sized and the other solution does not work: > > You can pass a block to Hash#new which gets called if the key does not > exist > >>> hsh = Hash.new {[]} > => {} >>> hsh[3] > => [] > > But this does not seem to work with Arrays... > >>> ary = Array.new {[]} > => [] >>> ary[2] > => nil > > Grettings > FreakGuard Hmmm...another approach: class DynamicArray < Hash attr_reader :length def initialize(length) @length = length super() {[]} end def []=(i, value) super @length = [i + 1, length].max end def to_a (0..length).to_a.collect{|i| self[i]} end def each(&block) self.to_a.each block end end ...and delegate everything else to self.to_a. Best, -- Marnen Laibow-Koser http://www.marnen.org marnen@marnen.org end -- Posted via http://www.ruby-forum.com/.