knight.moves
是其他位置的骑士实例数组。
如果我一起打印knight.position
和target
,有时它们是相同的,但该方法不会返回任何内容。
我认为它与块处理返回的方式有关,但我还没弄明白。
我的代码如下所示:
def dfs_rec knight, target
if knight
if knight.position == target
return knight
end
moves = knight.moves.size - 1
moves.times do |num|
dfs_rec knight.moves[num], target
end
end
end
答案 0 :(得分:1)
为什么不重构更像这样的东西?
class Knight
def at_position?(target_position)
position == target_position
end
def can_move_to?(target_position)
moves.include?(target_position)
end
end
# to find a knight in an array of knights that can move to `position`
knights.select { |knight| knight.can_move_to?(position) || knight.at_position?(position) } #=> [ <Knight>, <Knight> ]