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.
huang zhimin (Guest)
on 2007-06-10 07: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]]
unknown (Guest)
on 2007-06-10 07:18
(Received via mailing list)
In message
<removed_email_address@domain.invalid>, "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
Dan Z. (Guest)
on 2007-06-10 07:28
(Received via mailing list)
Peter S. 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.