From: Kevin Smith Date: 2000-12-16T13:20:45+09:00 Subject: [ruby-talk:7390] Re: Replacing nils in arrays? >On Fri, 15 Dec 2000 07:40:01 +0900, hal9000@hypermetrics.com wrote: >> Question for you all. >> >> Suppose you have an array that is growing >> more or less unpredictably. You assign an >> element that is past the current end, and >> you get several new nils as a result. >> >> My problem: I want to store zeroes, not >> nils. > >quick hack: > > >class Array > attr_accessor :default_value > > alias oldidx []= > def []=(*arg) > if arg.size == 3 > return oldidx(*arg) > end > > start, elem = arg > if start > size > fill @default_value, size, (start - size) > end > oldidx start, elem > end >end I would prefer to avoid storing the default value everywhere (in case ruby is smart enough to implement sparse arrays). Here's my stab (I'm new to dynamic languages, so I'll leave it to someone else to tweak this to change the actual Array class behavior. Actually, I'm not sure it ever should.) class ArrayWithDefault < Array attr_accessor : default def [](*arg) result = super if !result result = default elsif result.instance_of? Array result.collect! do | value | value ? value : default end end return result end end a1 = ArrayWithDefault.new a1[5] = 7 a1[2] = 4 puts a1[0..9] a1.default = 3 puts a1[0..9] Kevin