简体   繁体   English

如何在ruby中声明一个空的二维数组?

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

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. 我不知道如何在Ruby中做到这一点。

Pls help... 请帮忙......

You can do: 你可以做:

width = 2
height = 3
Array.new(height){Array.new(width)} #=> [[nil, nil], [nil, nil], [nil, nil]] 

To declare 2d array in ruby, Use following syntax with initialization value 要在ruby中声明2d数组,请使用以下语法和初始化值

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 我们可以进行任何级别的嵌套,比如3d数组(5 x 4 x 2):你可以在大多数内部数组中传递块来初始化数组

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 现在,您可以使用[]运算符来访问其元素,例如arr_2d [0] [1], actually its array of arrays

You can declare a multidimensional array in Ruby with: 您可以在Ruby中声明一个多维数组:

Array.new(Number_of_ROWs){Array.new(Number_of_COLUMNs)}

How To Use This Syntax 如何使用此语法

Let us understand it by using above example ie array = Array.new[2][2] . 让我们通过使用上面的例子来理解它,即array = Array.new[2][2]

So, in this example we've to declare an empty multidimensional array with 2 rows and 2 column. 因此,在这个例子中,我们要声明一个包含2行和2列的空多维数组。

Let us start implementing the our syntax now, 让我们现在开始实现我们的语法,

array = Array.new(2){Array.new(2)}

Now you've an array with 2 rows and 2 column with nil values. 现在你有一个包含2行和2nil值的array

Now the array variable contains [[nil, nil], [nil, nil]] which is consider as an empty multidimensional array or nil value multidimensional array . 现在array变量包含[[nil, nil], [nil, nil]] ,它被认为是一个empty multidimensional arraynil value multidimensional array

You could also initialize passing a value: 您还可以初始化传递值:

Array.new(3) { Array.new(3) { '0' } }

Output: 输出:

[
 ["0", "0", "0"], 
 ["0", "0", "0"], 
 ["0", "0", "0"]
]

简单地说:array = Array.new(8,Array.new(8))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM