# Multi-dimensional arrays

**URL:** <https://www.ruby-forum.com/t/multi-dimensional-arrays/97533>\
**Category:** Ruby\
**Created:** [July 7, 2006, 7:10pm UTC](https://www.ruby-forum.com/t/multi-dimensional-arrays/97533 "2006-07-07T19:10:45Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![gsiener](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/3ec8ea/32.png) [@gsiener](https://www.ruby-forum.com/u/gsiener)\
**Post date:** [July 7, 2006, 7:10pm UTC](https://www.ruby-forum.com/t/multi-dimensional-arrays/97533/1 "2006-07-07T19:10:45Z")

</div>

Hi,

I have just started programming with Ruby and have run into the  
following  
problem.

I’m trying to work with 3 dimensional arrays and have run into a problem  
dimensioning the array.

a = [[[]]]  
a[0][0] = [0,1,2,3]  
a[0][1] = [“zero”, “one”,“two”,three"]

The above assignments work without a problem, but the following  
assignment  
fails.

a[1][0] = [4, 5, 6, 7]  
NoMethodError: undefined method `[]=’ for nil:NilClass

How do you dimension the number of elements in a multi-dimensional array  
when  
the final number of elements in the array is not known.

–  
Regards,

Graham S.

---

<div class="post-metadata">

**Author:** ![gsiener](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/3ec8ea/32.png) [@gsiener](https://www.ruby-forum.com/u/gsiener)\
**Post date:** [July 7, 2006, 7:37pm UTC](https://www.ruby-forum.com/t/multi-dimensional-arrays/97533/2 "2006-07-07T19:37:32Z")

</div>

On Jul 7, 2006, at 12:09 PM, Graham S. wrote:

> How do you dimension the number of elements in a multi-dimensional  
> array when  
> the final number of elements in the array is not known.

Try [http://raa.ruby-lang.org/project/narray/](http://raa.ruby-lang.org/project/narray/)

- Jake McArthur

---

<div class="post-metadata">

**Author:** ![gsiener](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/3ec8ea/32.png) [@gsiener](https://www.ruby-forum.com/u/gsiener)\
**Post date:** [July 8, 2006, 6:57am UTC](https://www.ruby-forum.com/t/multi-dimensional-arrays/97533/3 "2006-07-08T06:57:11Z")

</div>

On Jul 7, 2006, at 1:09 PM, Graham S. wrote:

> a = [[[]]]  
> How do you dimension the number of elements in a multi-dimensional  
> array when  
> the final number of elements in the array is not known.
> 
> –  
> Regards,
> 
> Graham S.

class Array  
def default(&proc)  
@default = proc  
self  
end

alias\_method :rb\_array\_indexing, :"[]"  
def   
if @default and index.kind\_of? Integer and index \>= length  
index.downto(length) do |i|  
self[i] = @default.call(i)  
end  
end  
rb\_array\_indexing(index)  
end  
end

a = []  
a.default { [] }

a[1][0] = “Hello”  
a #=\> [[], [“Hello”]]
