On Nov 29, 2011, at 12:02 AM, Ryan Davis wrote:

>=20
> On Nov 28, 2011, at 06:34 , Sylvester Keil wrote:
>=20
>>=20
>> On Nov 28, 2011, at 3:17 PM, Gaurav C. wrote:
>>=20
>>> Douglas Seifert wrote in post #1034017:
>>>>>=20
>>>>>> a =3D Array.new(1e6+1) {|n| ""}
>>>>>=20
>>>>=20
>>>> The above creates an Array of 1,000,001 slots.  The block syntax =
lets
>>>> you
>>>> provide a default object dynamically.  The first time you reference =
a
>>>> particular index in the array, the block is called to allocate the
>>>> default
>>>> object at that position.
>>>>=20
>>>=20
>>> Hi Doug,
>>>=20
>>> Thanks for the explanation.
>>> Didn't understand the Array initialization part.
>>> What's the difference between Array.new(1e6+1) {|n| ""} and
>>> Array.new(1e6+1, "")?
>>=20
>> The former always returns a new string instance (this is what you =
want); the former creates one string and always returns a reference.
>=20
> I don't think this really explains it adequately.

You're absolutely right; what I was describing was more like default =
blocks on Hashes and not the behavior of Array.new.


> The former initializes the array by running the block on every index. =
The latter assigns the same object to every index.
>=20
> =46rom ri:
>=20
>  Array.new(size=3D0, obj=3Dnil)
>  Array.new(array)
>  Array.new(size) {|index| block }
>=20
> =
--------------------------------------------------------------------------=
----
>=20
> Returns a new array. In the first form, the new array is empty. In the =
second
> it is created with size copies of obj (that is, size
> references to the same obj). The third form creates a copy of the =
array
> passed as a parameter (the array is generated by calling to_ary  on =
the
> parameter). In the last 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.
>=20
>=20