From: Robert Klemme Date: 2009-11-20T01:17:50+09:00 Subject: Re: dynamic array? 2009/11/19 Marnen Laibow-Koser : > 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. What are you trying to achieve with this? As far as I can see you are mimicking Array behavior with a Hash. So you have created a sparse array but not a two dimensional array - which was what the OP wanted if I understand him properly. As a side note: I'd rather delegate to instead of inherit from Hash. The DynamicArray is not a Hash. For example, method #size remains in the interface which might lead to surprises. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/