Forum: Ruby nested arrays

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.
Mathias (Guest)
on 2006-02-22 19:56
(Received via mailing list)
Hi,

I'm new to this gem called ruby, but having difficulties generating
nested
arrays. Why is: var = Array.new(p, Array.new(q, 0)) not the same as:
var = Array.new(p) {Array.new(q, 0)} ?? (I know the later one works, but
it
took me ages for figuring this out :D)

Thnx for your answer.. Mathias
Robert K. (Guest)
on 2006-02-22 19:59
(Received via mailing list)
Mathias <removed_email_address@domain.invalid> wrote:
> Hi,
>
> I'm new to this gem called ruby, but having difficulties generating
> nested arrays. Why is: var = Array.new(p, Array.new(q, 0)) not the
> same as:
> var = Array.new(p) {Array.new(q, 0)} ?? (I know the later one works,
> but it took me ages for figuring this out :D)
>
> Thnx for your answer.. Mathias

Because in the first case you provide just a single object that is used
for
initialization while the second case you provide a code block that is
executed once for each array element to initialize.  Does that help?

Kind regards

    robert
Mathias (Guest)
on 2006-02-22 20:45
(Received via mailing list)
Hi Robert,

>> nested arrays. Why is: var = Array.new(p, Array.new(q, 0)) not the
>> same as:
>> var = Array.new(p) {Array.new(q, 0)} ?? (I know the later one works,
>> but it took me ages for figuring this out :D)
>>
>> Thnx for your answer.. Mathias
>
> Because in the first case you provide just a single object that is used
> for initialization while the second case you provide a code block that is
> executed once for each array element to initialize.  Does that help?

Yepp, and "language reference" says:
Array.new(size, obj) means [... is created with size copies of obj (that
is,
size references to the same obj)..] I possible read the _same_ over and
over again ;).


thanks for fast reply, Mathias
This topic is locked and can not be replied to.