Announcement (2017-05-07): www.ruby-forum.com is now read-only since I
unfortunately do not have the time to support and maintain the forum any
more. Please see rubyonrails.org/community and ruby-lang.org/en/community
for other Rails- und Ruby-related community platforms.

let me just give a blip of what i am getting...
>> a = Array.new(3,[])
=> [[], [], []]
>> a[2] << "check"
=> ["check"]
>> a
=> [["check"], ["check"], ["check"]]
this is totally not what i am expecting..
what i am expecting is:
[[],[],[["check"]]]
as in..
the 2 element should have the "check" string dropped into the next
available position..
how would i go about setting that (or any other) element only?
thanks!

Alle venerdÃ¬ 18 maggio 2007, Sergio Ruiz ha scritto:
> >> a>> the 2 element should have the "check" string dropped into the next> available position..>> how would i go about setting that (or any other) element only?>> thanks!
Look at the documentation for Array.new (ri Array.new). Array.new(n,
obj)
creates an array with n entries, all containing the same object, obj.
You can
see this comparing the entries' object_id, or using equal?:
a[0].equal?(a[1])
=> true. Since all entries contain the same object, when you modify it,
the
change shows everywhere in the array.
To fill the array with *different* empty arrays, you need to use the
form of
Array.new which takes a block:
Array.new(3){[]}
In this form, the block is called for each index, with the index as
argument
(you can omit it here because you don't need it). The result of the
block is
stored in the corresponding entry. The point is that each time the block
is
called, a *new* empty array is created and stored in the returned array.
This
time, a[0].equal?(a[1]) gives false.
I hope this helps
Stefano

In message <bcda57230145bdb94ab5011f83a1a769@ruby-forum.com>, Sergio
Ruiz writes:
>>> a = Array.new(3,[])>=> [[], [], []]>>> a[2] << "check">=> ["check"]>>> a>=> [["check"], ["check"], ["check"]]>>this is totally not what i am expecting..
I don't see why. You initialized an array with three copies of the SAME
empty
array.
-s

In message <f0314c659cd783e3f1a655cd7a5f9451@ruby-forum.com>, Mike
Fletcher writes:
>a = Array.new( 3 ) { |idx| Array.new() }>That will call the block once for each element, and that block will>create a new (different) array instance each time it's called.
You could just do {[]} for the block. It DWYM.
-s