Multi-dimensional arrays not working

I am trying to make a 3D grid using an Array of Arrays of Arrays but am
having trouble storing a single point with a value:

#2 by 2 by 2 grid
@grid = Array.new(2, Array.new(2, Array.new(2, “Null”)))

#Point (x, y, z)
#Point (0, 1, 1)
@grid[0][1][1] = ‘d’

#Print several points in grid
puts @grid[0][0][1]
puts @grid[0][1][1]
puts @grid[1][1][1]
puts @grid[0][0][0]
puts @grid[0][1][0]
puts @grid[1][1][0]

The code returns all values with z = 1 as ‘d’ and z = 0 as ‘null’… It
should really be only making the point (0, 1, 1) as ‘d’ right?!?!?

If the above line “@grid[0][1][1] = ‘d’” is changed, the only value that
will change the results is the z value…

I want it so that only “puts @grid[0][1][1]” returns ‘d’… The actual
code contains more methods and stuff, but I think I’ve isolated the
problem to this… Any info, tutorials, links, or code would be greatly
appreciated.

Array’s initial value is not copied to each block, but every field
indicates the same object.
So, @grid should be initialized in the following way.

@grid = Array.new(2).collect{ Array.new(2).collect{
Array.new(2).collect{ “Null”}}}

On ruby 1.7 or later,
@grid = Array.new(2){ Array.new(2){ Array.new(2){ “Null”}}}
is OK, too.

There are some sample codes for such case.
Sorry, I could not find English edition.
http://www.ruby-lang.org/ja/man/html/trap_Array.html

Haruka YAGNI wrote in post #985681:

Array’s initial value is not copied to each block, but every field
indicates the same object.
So, @grid should be initialized in the following way.

@grid = Array.new(2).collect{ Array.new(2).collect{
Array.new(2).collect{ “Null”}}}

Thanks! Worked perfectly… I was trying to figure out why it wasn’t
working… makes a lot more sense now though.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs