On Oct 9, 10:40 am, Stephan Mueller <d4... / web.de> wrote:
> * Robert Dober <robert.do... / gmail.com> [09.10.2007]:
> > c[:test] or "default"
>
> nice! But in my case I will need the block because
>
> a) in practice a simple literal will not suffice

You're not limited to a simple literal.

> b) the result of the block should be assigned to the internal array at
> the same step. (this was not part of my example code, sorry)

Your example seems more hash-like than array-like to me, and it sounds
like using the same technique that Hash uses (passing a block to
Hash.new for default value computation) may work for you if the
computed value is a function of the object and/or the key.

class MyClass
  def initialize obj=nil, &b
    if block_given?
      @default_block = b
    elsif obj
      @default_block = lambda {|h,k| obj }
    end
    @h = Hash.new
  end

  def [](key)
    if !@h.has_key?(key) && @default_block
      @h[key] = @default_block.call(self, key)
      puts "'#{@h[key]}' assigned to #{key}"
    end
    @h[key]
  end

  def []=(key, value)
    @h[key] = value
  end
end

c = MyClass.new('default')
c[:foo] = 'foo'
puts c[:foo]
puts c[:test]
c = MyClass.new {|obj,key| "default for #{key}" }
puts c[:test]