# Creating a 2d array

Hi im just coming to ruby from C albeit after many years of no
programming. Im trying the simple matrix problem to get used to dealing
with arrays in ruby.

How do you create a blank 2d array?

I want to ask the user for the number of rows and columns and then
create a blank 2d array using those dimensions. From there I’d populate
it with the users desired data.

Cheers

On Feb 2, 2008 11:55 AM, Adam A. [email protected]lid wrote:

Cheers
x, y = 2, 3 #you get these values from the user
m = [] #initializing m for scope reasons
x.times { m << Array.new( y ) } # adding new arrays to m

That should get you started. Keep in mind that arrays are just
ordered lists of objects. You can have an ordered list of any object
(including other arrays). The [] index call can be chained. So to
access this 2d array at 0,0 you would do m[0][0].

hth,
Todd

thanks that does help indeed.

x, y = 2, 3 #you get these values from the user
m = [] #initializing m for scope reasons
x.times { m << Array.new( y ) } # adding new arrays to m

Or maybe:

Array.new(x) {Array.new(y)}

On Feb 2, 2008 12:55 PM, Adam A. [email protected] wrote:

Hi im just coming to ruby from C albeit after many years of no
programming. Im trying the simple matrix problem to get used to dealing
with arrays in ruby.

There is a matrix class in the stdlib. But if you’re doing anything
numeric, I’d recommend using NArray.

How do you create a blank 2d array?

I want to ask the user for the number of rows and columns and then
create a blank 2d array using those dimensions. From there I’d populate
it with the users desired data.

Todd’s suggestion will work, but I prefer:
rows, cols = 2,3
mat = Array.new(rows) { Array.new(cols) }

Cameron

Todd’s suggestion will work, but I prefer:
rows, cols = 2,3
mat = Array.new(rows) { Array.new(cols) }

Cameron

Why do you use the {}? Arent they used when your creating hashes.

This is a block (like do…end), not a Hash, in this context.
The block is passed to the Array constructor and which calls it
with each index to yield a value for the elements of the outer
array being constructed.

Clifford H…

Ok i think i kinda understand. Could you tell me if this is something
specific to arrays or is it used for other objects as well? If I wanted
index/contents?

Todd’s suggestion will work, but I prefer:
rows, cols = 2,3
mat = Array.new(rows) { Array.new(cols) }

Cameron

Why do you use the {}? Arent they used when your creating hashes.

Ok i think i kinda understand. Could you tell me if this is something
specific to arrays or is it used for other objects as well? If I wanted