Forum: Ruby Strange behavior of Array

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.
13c60e2a5806406b537daa542d3495da?d=identicon&s=25 huang zhimin (Guest)
on 2007-06-10 05:14
(Received via mailing list)
I want a multidimensional array with initial value 0, so I create it by

arr = Array.new(3, Array.new(3, 0))    =>     [[0, 0, 0], [0, 0, 0], [0,
0,
0]]

now I change the arr[0][0] to 1

arr[0][0] = 1
arr    =>    [[1, 0, 0], [1, 0, 0], [1, 0, 0]]

It's so strange for me, why it's not [[1, 0, 0], [0, 0, 0], [0, 0, 0]]
B8cfd5ec0f88bf5b5f2eedda7d1a0746?d=identicon&s=25 unknown (Guest)
on 2007-06-10 05:18
(Received via mailing list)
In message
<ae8a916c0706092013w592e1730y59b0c9d7d55d7005@mail.gmail.com>, "huang
zhimin" writes
:
>I want a multidimensional array with initial value 0, so I create it by

>arr = Array.new(3, Array.new(3, 0))    =>     [[0, 0, 0], [0, 0, 0], [0, 0,
>0]]

You have now created an array consisting of three copies of the SAME
array [0,0,0].

This is a FAQ.

-s
Caf38c89d40443a858741b61ac6d82de?d=identicon&s=25 Dan Zwell (Guest)
on 2007-06-10 05:28
(Received via mailing list)
Peter Seebach wrote:
> This is a FAQ.
>
> -s
>
>

Yeah, but at least give the guy a link to the correct solution, or
something.

This is how you do it:
arr = Array.new(3) { Array.new(3, 0) }

Dan
This topic is locked and can not be replied to.