Ruby:如果语句给出"未定义的方法"错误

时间:2014-05-13 08:30:37

标签: ruby runtime-error

我最近一直在尝试使用Chris Pine的Learn to Program学习ruby,在第10章他给出了一个递归代码来计算大陆的大小

M = 'land'
O = 'water'

world = [[O, O, O, M, O, O, O, O], 
         [O, O, M, M, O, O, M, O], 
         [M, M, M, M, M, O, O, M], 
         [M, M, O, M, O, O, O, O],
         [O, M, M, M, M, O, O, O],
         [O, O, M, M, O, M, M, M], 
         [O, O, M, O, O, O, O, O]]

def continent_size world, x, y
    if world[y][x] != M
        return 0
    end

    size = 1
    world[y][x] = 'counted'

    size += continent_size world, x-1, y-1
    size += continent_size world, x, y-1
    size += continent_size world, x+1, y-1
    size += continent_size world, x-1, y
    size += continent_size world, x+1, y
    size += continent_size world, x-1, y+1
    size += continent_size world, x, y+1
    size += continent_size world, x+1, y+
    size
end
puts continent_size world, 5, 5
他在书中指出,如果某些土地附着在边缘上,这个代码就会出错(正如你所看到的那样,我试过了),但代码运行得很好。 当我尝试添加非常简单的检查时,如:

def continent_size world, x, y
    if y < 0
        return 0
    end
    if world[y][x] != M
        return 0
    end
    .
    .

我突然得到&#34;未定义的方法&#39; []&#39;为零:NilClass&#34;错误&#34;如果世界[y] [x]!= M&#34;我真的不知道发生了什么改变了。这个错误来自哪里?

编辑:经过一些测试后,现在的问题似乎是数字超出限制,因为以下内容确实有效:

def continent_size (world, x, y)
    if y < 0 || y > 6 || x < 0 || x > 7
        return 0
    end
    if world[y][x] != M
        return 0
    end
    .
    .

我仍然感到困惑,为什么原始代码没有问题,但

1 个答案:

答案 0 :(得分:1)

你有边缘的问题,如果你的世界是5x5然后你正在呼叫世界[6] [6]反对它(负数仍然有效)。 world [6]返回nil,它没有定义[]方法。

要修复它,您需要添加:

def continent_size world, x, y
  if y < 0 || world[y].nil? || world[y][x] != M
    return 0
  end
相关问题