1

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

1
  • Unless I am missing something, I don't think it supports more than 2 dimensions? Commented Feb 11, 2017 at 4:06

1 Answer 1

2

This calls for a recursive method.

def make_nested_array(*dim, v)
  d, *rest = dim
  Array.new(d) { rest.empty? ? v : make_nested_array(*rest, v) }
end

a = make_nested_array(2,3,4,'hi')
  #=> [
  #     [
  #       ["hi", "hi", "hi", "hi"], ["hi", "hi", "hi", "hi"], ["hi", "hi", "hi", "hi"]
  #     ],
  #     [
  #       ["hi", "hi", "hi", "hi"], ["hi", "hi", "hi", "hi"], ["hi", "hi", "hi", "hi"]
  #     ]
  #   ] 

To demonstrate no two object_id's are the same, let's change just one element.

a[1,1,1] = 'cat'
a.flatten
  #=> ["hi", "hi", "hi", "hi", "hi", "hi",  "hi", "hi", "hi", "hi", "hi", "hi",
  #    "hi", "hi", "hi", "hi", "hi", "cat", "hi", "hi", "hi", "hi", "hi", "hi"] 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.