From: Dave Thomas Date: 2000-06-08T07:36:13-05:00 Subject: [ruby-talk:03194] Re: 3-d arrays? Hugh Sasse Staff Elec Eng writes: > So the sensible thing seems to be to just have a flat array and > provide methods for the indexing, which is pretty much what I did in C++. > In C++ you cannot overload [][][], so I suppose that is true for Ruby > as well, is it? You can overload [] (and []=, to provide your own array referencing semantics. ## Untested class ThreeDArray def initialize(maxx, maxy) @maxx, @maxy = maxx, maxy @content = [] # this is where I'll keep the actual content end def index(x, y, z) ((x*@maxx) + y)*@maxy + z end def [](x, y, z) @content[index(x, y, z)] end def []=(x, y, z, newVal) @content[index(x, y, z)] = newVal end end # Well, almost untested... a = ThreeDArray.new(3, 3) for i in 0..2 for j in 0..2 for k in 0..2 a[i, j, k] = i * j * k end end end for i in 0..2 for j in 0..2 for k in 0..2 printf "%4d", a[i, j, k] end puts end puts end #=> 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 0 2 4 0 0 0 0 2 4 0 4 8 In fact, it wouldn't be hard to extend this one class to handle n-dimensional arrays, where 'n' is determined as each object is created. Regards Dave