原です。 > こまいです。先日、 > > dat = Array.new(imax) > for i in 0..imax-1 > dat[i] = Array.new(jmax) > for j in 0..jmax-1 > dat[i][j] = Array.new(kmax) > for k in 0..kmax-1 > dat[i][j][k] = hoge.new > end > end > end > > のように 3次元配列を使うことがあったのです > が、どうもスマートでないような気がしました。 やっぱり MDArray を使うのが正解かと思いますが、再帰を使って 書いてみました。(かなり複雑 ^^;) def Array.tensor(sizes, data=[], i = nil) if size = sizes[0] array = new(size) data[-1][i] = array if i data += [array] array.each_index { |i| tensor(sizes[1..-1], data, i) {|*x| yield(i, *x)} } else data[-1][i] = yield if i return end data[0] end これで dat = Array.tensor([imax, jmax, kmax]) { |*x| hoge.new } とできます。 テスト用のスクリプトも添えておきます。 class Array def each_elements each_index { |i| if self[i].is_a? Array self[i].each_elements { |*x| yield(i, *x) } else yield i end } end def at(*x) d = self x.each { |i| d = d[i] } d end end dat = Array.tensor([2,2,2,2]) { |*x| x.inspect } dat.each_elements { |*x| printf("%s -> %s\n", x.inspect, dat.at(*x)) }