Ruby multidimensional array

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

    Here is an implementation of a 3D array class in ruby, in this case the default value is 0

    class Array3
     def initialize
       @store = [[[]]]
     end
    
     def [](a,b,c)
      if @store[a]==nil ||
        @store[a][b]==nil ||
        @store[a][b][c]==nil
       return 0
      else
       return @store[a][b][c]
      end
     end
    
     def []=(a,b,c,x)
      @store[a] = [[]] if @store[a]==nil
      @store[a][b] = [] if @store[a][b]==nil
      @store[a][b][c] = x
     end
    end
    
    
    array = Array3.new
    array[1,2,3] = 4
    puts array[1,2,3] # => 4
    puts array[1,1,1] # => 0
    

提交回复
热议问题