On May  1, Orion Hunter wrote:
> I am trying to create an array of certain length, with a default value of 
> Array.new (such that I will have an array of arrays).  I cannot use the 
> "default" parameter setting Array.new( 4, Array.new ) because I end up with 
> an array populated with references to the same array.  For example:
> 
>    irb> a = Array.new( 4, Array.new )
>    irb> [ [], [], [], [] ]
>    irb> a[0][0] = 1
>    irb> a
>    irb> [ [1], [1], [1], [1] ]
> 
> After some thought, this result was not surprising.  The interpreter 
> evaluates the Array.new parameter before passing, thus it ends up passing a 
> reference, and this single reference gets populated into each element, 
> instead of a new array into each.
> 

[snip]

In 1.8, you can use (pasted from ri 1.8):

     Array.new( size ) {| i | block } -> anArray

     In [this] form, an array of the given size is created. Each element in
this array is calculated by passing the element's index to the given block and
storing the return value.

        squares = Array.new(5) {|i| i*i}
        squares             #=> [0, 1, 4, 9, 16]



So, for your purposes:

irb(main):001:0>   a = Array.new(4) { |i| [] }
[[], [], [], []]
irb(main):002:0> a[0].push("foo")
["foo"]
irb(main):003:0> a[2].push("bar")
["bar"]
irb(main):004:0> a
[["foo"], [], ["bar"], []]


I hope that helps, it helped me when Guy pointed out the same feature for
Hashes.

---------------------------------------------- | --------------------------
Brett Williams                                 | (970) 288-0475        
Agilent Technologies                           | brett_williams / agilent.com
---------------------------------------------- | --------------------------