Forum: Ruby Probleme with 2-dimensionnal 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.
1213acd137806b718b75a4fa27c0b546?d=identicon&s=25 Erard Sebastien (z720)
on 2006-04-19 18:03
I can't understand why this piece of code doesn't return the array
expected ?

my_array = Array.new(3, Array(3))

3.times do |i|
  3.times do [j|
    my_array[i][j] = i + j
  end
end

it should return :
[[ 0, 1, 2] [1, 2, 3] [2, 3, 4]]

but it returns :
[[2, 3, 4] [2, 3, 4] [2, 3, 4]]

Is my code wrong ?
If so how could I build the expected array ?

Thank you
81d609425e306219d54d793a0ad98bce?d=identicon&s=25 Matthew Moss (Guest)
on 2006-04-19 18:11
(Received via mailing list)
It has to do with how you construct your array.  Your outer array
contains 3 references to the same inner array.

You need to force each inner array to be a separate object, which can
be done like this:

my_array = Array.new(3) { Array.new(3) }
1213acd137806b718b75a4fa27c0b546?d=identicon&s=25 Erard Sebastien (z720)
on 2006-04-19 18:14
Matthew Moss wrote:
> It has to do with how you construct your array.  Your outer array
> contains 3 references to the same inner array.
>
> You need to force each inner array to be a separate object, which can
> be done like this:
>
> my_array = Array.new(3) { Array.new(3) }

Perfect thank you very much...
4299e35bacef054df40583da2d51edea?d=identicon&s=25 James Gray (bbazzarrakk)
on 2006-04-19 19:57
(Received via mailing list)
On Apr 19, 2006, at 11:03 AM, Erard Sebastien wrote:

> I can't understand why this piece of code doesn't return the array
> expected ?
>
> my_array = Array.new(3, Array(3))

my_array = Array.new(3) { Array.new }

> [[2, 3, 4] [2, 3, 4] [2, 3, 4]]
>
> Is my code wrong ?

The two argument form of the constructor uses the same object in each
slot.  Thus, if you change one, all are modified.  The block form I
used above will be called to generate each object, getting you the
desired results.

Hope that helps.

James Edward Gray II
This topic is locked and can not be replied to.