Ruby multidimensional array

前端 未结 11 1402
春和景丽
春和景丽 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:41

    Strictly speaking it is not possible to create multi dimensional arrays in Ruby. But it is possible to put an array in another array, which is almost the same as a multi dimensional array.

    This is how you could create a 2D array in Ruby:

    a = [[1,2,3], [4,5,6], [7,8,9]]
    


    As stated in the comments, you could also use NArray which is a Ruby numerical array library:

    require 'narray'
    b = NArray[ [1,2,3], [4,5,6], [7,8,9] ]
    

    Use a[i][j] to access the elements of the array. Basically a[i] returns the 'sub array' stored on position i of a and thus a[i][j] returns element number j from the array that is stored on position i.

提交回复
热议问题