Dmitriy Genzel
4/25/2005 8:44:00 PM
Better yet, I think Array.new in the -w mode should check if it got
called with a second argument that responds to "each" or
perhaps to "[]=" and warn. I can't think of any meaningful use for
Array.new(n, Array.new) or of any use where a container is given
as a default argument of an array in such a manner.
And the same should apply to Hash.new.
Just about any newbie (especially with Perl background) runs into this,
I think. I know I did.
Dmitriy
On Apr 25, 2005, at 10:44 AM, Robert Klemme wrote:
>
> "Gavin Kistner" <gavin@refinery.com> schrieb im Newsbeitrag
> news:b3bc6362698d8da96cf5b6d43cb334f1@refinery.com...
>> On Apr 25, 2005, at 8:09 AM, Robert Klemme wrote:
>>>> 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"}]
>>
>> Though even then, it would appear (to someone wanting the specific
>> functionality of the OP, and probably 'most' cases) that the parameter
>> is used as a template, with .dup used for each instance.
>
> Probably.
>
>> I think the
>> example should illustrate that the objects are in fact the same, and
>> discuss the end result each has:
>>
>> my_array = Array.new( 2, { :foo => :bar } )
>> my_array[ 1 ][ :jimmy ] = :jammy
>> p my_array
>> #=> [{:foo=>:bar, :jimmy=>:jammy}, {:foo=>:bar, :jimmy=>:jammy}]
>>
>> my_array = Array.new( 2 ){ { :foo => :bar } }
>> my_array[ 1 ][ :jimmy ] = :jammy
>> p my_array
>> #=> [{:foo=>:bar}, {:foo=>:bar, :jimmy=>:jammy}]
>
> Nice, too. Or do
>
>>> a = Array.new(2, {"foo"=>"bar"})
> => [{"foo"=>"bar"}, {"foo"=>"bar"}]
>>> a.map{|o| o.object_id}
> => [135028744, 135028744]
>>> a.map{|o| o.object_id}.uniq
> => [135028744]
>
> Kind regards
>
> robert
>
>