First off, let me say I am new to Ruby and that I heard about NArray but I'd like to see if I can attempt to solve this (with some help from you fine folks)
I learned that I could do something like this:
a=Array.new(2){Array.new(2){Array.new(2,5)}}
=>[[[5, 5], [5, 5]], [[5, 5], [5, 5]]]
from Ruby multidimensional array
I tried to make a generic function like that could take any variables as dimensions, and fill the n dimensional array with a value:
def get_n_dimensional(*args, value)
myarr= Array.new(args[-1],value)
args.reverse.drop(1).each{ |arg| myarr=Array.new(arg){myarr}}
return myarr
end
a = get_n_dimensional(2,2,2,value=5)
puts a.inspect
=> [[[5, 5], [5, 5]], [[5, 5], [5, 5]]]
But I can see how referencing the same array recursively causes problems:
a[0][1][1]=100
puts a.inspect
=> [[[5, 5], [5, 100]], [[5, 5], [5, 100]]]
I'm wondering about other strategies I can use to solve this. I was thinking of perhaps building a string (with looping that depends on the input dimensions) and evaluating it in my function such as:
eval("Array.new(args[0]){Array.new(args[1]){Array.new(args[2],value)}}"
I guess part of my question is if its okay to rely on eval like this
Also this is my first post on SO...let me know if I messed up