Create two-dimensional arrays and access sub-arrays in Ruby

前端 未结 9 1006
走了就别回头了
走了就别回头了 2020-11-28 03:26

I wonder if there\'s a possibility to create a two dimensional array and to quickly access any horizontal or vertical sub array in it?

I believe we can access a hor

9条回答
  •  时光说笑
    2020-11-28 03:49

    Here's a 3D array case

    class Array3D
       def initialize(d1,d2,d3)
        @data = Array.new(d1) { Array.new(d2) { Array.new(d3) } }
       end
    
      def [](x, y, z)
        @data[x][y][z]
      end
    
      def []=(x, y, z, value)
        @data[x][y][z] = value
      end
    end
    

    You can access subsections of each array just like any other Ruby array. @data[0..2][3..5][8..10] = 0 etc

提交回复
热议问题