Robert Klemme
10/12/2004 1:31:00 PM
"Brian Candler" <B.Candler@pobox.com> schrieb im Newsbeitrag
news:20041012124216.GA38956@uk.tiscali.com...
> a = Array.new { [] }
> p a #=> []
> p a[3] #=> nil
>
> Just checking: you can't have an Array whose elements spring into life
when
> needed (as you can with a Hash)?
>
> Maybe a good thing - you might not want a single access to a[10000] to
> create that many objects - but it could be useful on occasions.
>
> No need to post other solutions - I can subclass/delegate such that [],
[]=
> are overridden appropriately, although usually I just end up writing
You only need to override [], do you?
Btw, this raises an interesting question about the desired semantics of
auto creation: should it kick in for all elements that are nil or just for
those beyond the array limits? Should it create just a single instance or
fill all newly created cells?
I'd opt for 1.2 and 2.1, i.e., only the element accessed is created if
they are nil. This feels the most close to Hash. This would be the impl
I'd choose:
class AutoArray < Array
NILLER = lambda { nil }
def initialize(*x, &b)
super(*x)
@missing = b || NILLER
end
def [](idx)
super || @missing.call(self, idx)
end
end
a = AutoArray.new {|a,idx| a[idx]=[]}
Kind regards
robert