Ruby multidimensional array

前端 未结 11 1491
春和景丽
春和景丽 2020-11-28 09:30

Maybe it\'s just my lack of abilities to find stuff here that is the problem, but I can\'t find anything about how to create multidimensional arrays in Ruby.

Could s

11条回答
  •  天命终不由人
    2020-11-28 09:51

    you can pass a block to Array.new

    Array.new(n) {Array.new(n,default_value)}
    

    the value that returns the block will be the value of each index of the first array,

    so..

    Array.new(2) {Array.new(2,5)} #=> [[5,5],[5,5]]
    

    and you can access this array using array[x][y]

    also for second Array instantiation, you can pass a block as default value too. so

    Array.new(2) { Array.new(3) { |index| index ** 2} } #=> [[0, 1, 4], [0, 1, 4]]
    

提交回复
热议问题