From: mathew
Date: 2005-10-12T06:51:53+09:00
Subject: Re: multi-dimensional Arrays
Peter v. N. wrote:
> I know there exist "simple" ways (Google's thy friend)
> to create md arrays with Ruby. But it's somehow cumbersome
> and it would be nice if it could be done like "array = Array.new(3,3)"
require 'pp'
# Create and initialize a multi-dimensional array
# given an array of its required dimensions
# and an initial value for all cells
def ArrayFactory(dimensions, initialvalue)
size = dimensions.first
if dimensions.length == 1
return Array.new(size, initialvalue)
else
rest = dimensions[1,dimensions.length-1]
a = Array.new(size)
for i in 0..size
a[i] = ArrayFactory(rest, initialvalue)
end
return a
end
end
a = ArrayFactory([3, 5, 7], "Hi!")
pp a
a[2][3][7] = "Hello!"
puts a[2][3][7]
pp a[2][3]
Or see the various enhanced Array classes on RubyForge etc.
mathew
--
WE HAVE TACOS