Ruby Shoes中的多维数组不能按预期工作

时间:2014-12-06 14:27:06

标签: ruby arrays matrix

我正在尝试创建一个方法来创建一个矩阵并用特定的值填充它但是由于一些奇怪和意想不到的原因,在while循环中标记为注释的指令根本不起作用,我做错了什么?这是代码:

def map(r,c)

    row = 0 #row counter
    map = Array.new

    while (row < r)

        map[row] = Array.new #Creates an array with row Rows

        col = 0 #col counter

        while (col < c)

            map[row][col] = 0 #Floor
            map[0][col]   = 1 #Top wall
            #map[r][col]   = 2 #Bottom wall
            map[row][0]   = 3 #Left wall
            map[row][c]   = 4 #Right wall
            map[0][0]     = 5 #Top left corner
            map[0][c]     = 6 #Top right corner
            #map[r][0]     = 7 #Bottom left corner
            #map[r][c]     = 8 #Bottom right corner

            col = col + 1
        end
        row = row + 1
    end
    alert(map)
end

Shoes.app(:width => 650,:height => 450) do
    map(17,22)
end

1 个答案:

答案 0 :(得分:1)

当您尝试为ruby中超出其边界的数组赋值时,该数组将填充nil直到该点,并将值设置在正确的位置:

a = []
a[5] = 5
puts a
# => [nil, nil, nil, nil, nil, 5]

如果你试图得到一个超出数组范围的值,你得到nil

a = []
a[5]
# => nil

这就是为什么当您尝试分配map[r][col] = 2时会收到错误,因为map[r]nil

要解决此问题,您需要使用map空数组预先填充r数组:

map = Array.new(r+1) { [] }

这种方式map[r]不会返回nil,您可以设置其值:

def map(r,c)

    row = 0 #row counter
    map = Array.new(r+1) { [] }

    while (row < r)

        col = 0 #col counter

        while (col < c)

            map[row][col] = 0 #Floor
            map[0][col]   = 1 #Top wall
            map[r][col]   = 2 #Bottom wall
            map[row][0]   = 3 #Left wall
            map[row][c]   = 4 #Right wall
            map[0][0]     = 5 #Top left corner
            map[0][c]     = 6 #Top right corner
            map[r][0]     = 7 #Bottom left corner
            map[r][c]     = 8 #Bottom right corner

            col = col + 1
        end
        row = row + 1
    end
    alert(map)
end

Shoes.app(:width => 650,:height => 450) do
    map(17,22)
end