"Adriano Ferreira" <a.r.ferreira / gmail.com> schrieb im Newsbeitrag
news:73ddeb6c0504250552da67f6 / mail.gmail.com...
> > foo = Array.new(3,Array.new)
> > foo = Array.new(3,[])
>
> I think these are just the same.

Nearly: with Array.new you cannot provide a list of values like with [] -
but apart from that: yes, "[]" is syntactical sugar for "Array.new"
followed by some element additions.

> Indeed, the object creation ([] or
> Array.new) happens only once.

That's the crucial part to understand: "[]" or "Array.new" is an argument
to a method invocation (Array.new) so it's evaluated *once before* the
method is invoked and the second parameter is bound to this value.
Perfectly logical and reasonable.

> To have distinct arrays in every slot of
> foo you need something like
>
> foo = Array.new(3) { Array.new }
> foo[0] << 4
> foo[1] << 5
> foo[0] << 6
> p foo
>
> (as Dave Baldwin suggested) and you'll get
>
> [[4, 6], [5], []]
>
> If you come to this code, by looking at the Array documentation where
> the example
>             Array.new(2, Hash.new)  [{}, {}]
> is given, I agree that this documentation is misleading for beginners.

Yep, true.  Probably a better example would be

>> Array.new(2, {"foo"=>"bar"})
=> [{"foo"=>"bar"}, {"foo"=>"bar"}]

Kind regards

    robert