Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare an empty 2-dimensional array in ruby?

Tags:

can somebody pls tell me how to declare a new instance of 2-dimensional array? Most of the languages uses something like

array = Array.new[2][2]

I don't know how to do it in Ruby.

Pls help...

like image 573
johan Avatar asked Mar 21 '11 00:03

johan


People also ask

How do you create an empty array in Ruby?

You can create an empty array by creating a new Array object and storing it in a variable. This array will be empty; you must fill it with other variables to use it. This is a common way to create variables if you were to read a list of things from the keyboard or from a file.

How do you declare a 2D array?

To declare a 2D array, specify the type of elements that will be stored in the array, then ( [][] ) to show that it is a 2D array of that type, then at least one space, and then a name for the array. Note that the declarations below just name the variable and say what type of array it will reference.


2 Answers

You can do:

width = 2
height = 3
Array.new(height){Array.new(width)} #=> [[nil, nil], [nil, nil], [nil, nil]] 
like image 160
Mike Lewis Avatar answered Sep 22 '22 03:09

Mike Lewis


To declare 2d array in ruby, Use following syntax with initialization value

row, col, default_value = 5, 4, 0
arr_2d = Array.new(row){Array.new(col,default_value)}
=> [[0, 0, 0, 0], 
    [0, 0, 0, 0], 
    [0, 0, 0, 0], 
    [0, 0, 0, 0], 
    [0, 0, 0, 0]]

We can do any level of nesting, like for 3d array(5 x 4 x 2): you can pass block to initialize array in most inner Array

z = 2
arr_3d = Array.new(row){Array.new(col){Array.new(z){|index| index}}}
=> [[[0, 1], [0, 1], [0, 1], [0, 1]], 
    [[0, 1], [0, 1], [0, 1], [0, 1]], 
    [[0, 1], [0, 1], [0, 1], [0, 1]], 
    [[0, 1], [0, 1], [0, 1], [0, 1]], 
    [[0, 1], [0, 1], [0, 1], [0, 1]]]

Now, you can access its element using [] operator like arr_2d[0][1], actually its array of arrays

like image 22
aqfaridi Avatar answered Sep 20 '22 03:09

aqfaridi