From: Shashank Date Date: 2002-12-09T07:23:22+09:00 Subject: Re: multi-dimension array "Shannon Fang" wrote in message news:20021208193614.A604.XRFANG@hotmail.com... > Hi there, > > I am a little confused about multi-dimension array definition in ruby. It's OK ... it is confusing in the beginning to most of us (especially if coming from C background) > I tried the following > a=Array.new(3,Array.new(2,Array.new)) > p a > > out put is: > [[[ ], [ ]], [[ ], [ ]], [[ ], [ ]]] Correct ! It did what you asked it do ... reading Array.new from inside out: First create an Array object with no elements (like []) Then use it as the initial value of another Array object with 2 elements. Then use this as the initial value of the final Array object with 3 elements. Hence: [[[ ], [ ]], [[ ], [ ]], [[ ], [ ]]] Moreover, if you tried: a[0][0][0] = 1 p a you would now get [[[1], [1]], [[1], [1]], [[1], [1]]] Surprised, eh ? > What I need is a 2 dimesional array a, with the following elements > a[0][0] > a[0][1] > a[1][0] > a[1][1] > a[2][0] > a[2][1] Then you should try : a = Array.new(2,Array.new(2,0)) p a [[0,0],[0,0],[0,0]] But then again, a[0][0] = 1 p a will give you : [[1, 0], [1, 0]] So the other approach is: arr = Array.new(2) arr.each_index { |i| r = Array.new(2) r.each_index { |j| r[j] = 0 } arr[i] = r } p arr will give you: [[0,0],[0,0],[0,0]] Now if you do: arr[0][0] = 1 p arr you will get: [[1,0],[0,0],[0,0]] Is that what you wanted ? HTH, -- shanko