Auto-created Array elements?

B

Brian Candler

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

a[x] ||= []
a[x][y] = 'whatever'

Regards,

Brian.
 
T

ts

B> a = Array.new { [] }

svg% ruby -we 'Array.new { [] }'
-e:1: warning: given block not used
svg%


Guy Decoux
 
R

Robert Klemme

Brian Candler said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top