Ruby multidimensional array

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

    It might help to remember that the array is an object in ruby, and objects are not (by default) created simply by naming them or naming a the object reference. Here is a routine for creating a 3 dimension array and dumping it to the screen for verification:

    def Create3DimensionArray(x, y, z, default)
        n = 0                       # verification code only
        ar = Array.new(x)
        for i in 0...x
            ar[i] = Array.new(y)
            for j in 0...y
                ar[i][j] = Array.new(z, default)
                for k in 0...z      # verification code only
                    ar[i][j][k] = n # verification code only
                    n += 1          # verification code only
                end                 # verification code only
            end
        end
        return ar
    end
    
    # Create sample and verify
    ar = Create3DimensionArray(3, 7, 10, 0)
    
    for x in ar
        puts "||"
        for y in x
            puts "|"
            for z in y
                printf "%d ", z
            end
        end
    end

提交回复
热议问题