我正在重构一些代码,这个proc随机地导致了一个错误,我不知道为什么或者如何调试它.有什么想法吗?
使用proc的新代码
defense_moves, offense_moves = [], []
determine_move = ->move,side,i { side << move.count(move[i]) }
defense.size.times { |i| determine_move.(defense, defense_moves, i) }
offense.size.times { |i| determine_move.(offense, offense_moves, i) }
dm = defense[defense_moves.index(defense_moves.max)].nil? ? [0] : defense[defense_moves.index(defense_moves.max)]
om = offense[offense_moves.index(offense_moves.max)].nil? ? [0] : offense[offense_moves.index(offense_moves.max)]原始代码:
d = 0
defense_moves = []
loop do
defense_moves << defense.count(defense[d])
break if defense.count(defense[d]).zero?
d += 1
end
o = 0
offense_moves = []
loop do
offense_moves << offense.count(offense[o])
break if offense.count(offense[o]).zero?
o += 1
end
dm = defense[defense_moves.index(defense_moves.max)].nil? ? [0] : defense[defense_moves.index(defense_moves.max)]
om = offense[offense_moves.index(offense_moves.max)].nil? ? [0] : offense[offense_moves.index(offense_moves.max)]TypeError
ttt2.rb:95:in `[]': no implicit conversion from nil to integer (TypeError)
from ttt2.rb:95:in `computer_make_move'
from ttt2.rb:133:in `draw_board'
from ttt2.rb:24:in `place'
from ttt2.rb:209:in `block in start_new_game'
from ttt2.rb:188:in `loop'
from ttt2.rb:188:in `start_new_game'
from ttt2.rb:199:in `block in start_new_game'
from ttt2.rb:188:in `loop'
from ttt2.rb:188:in `start_new_game'
from ttt2.rb:199:in `block in start_new_game'
from ttt2.rb:188:in `loop'
from ttt2.rb:188:in `start_new_game'
from ttt2.rb:199:in `block in start_new_game'
from ttt2.rb:188:in `loop'
from ttt2.rb:188:in `start_new_game'
from ttt2.rb:199:in `block in start_new_game'
from ttt2.rb:188:in `loop'
from ttt2.rb:188:in `start_new_game'
from ttt2.rb:234:in `<main>'发布于 2014-06-03 04:36:06
所以,在代码出现之前:
defense_moves, offense_moves = [], []
determine_move = -> move, side, i { side << move.count(move[i]) }
(defense.size + 1).times { |i| determine_move.(defense, defense_moves, i) }
(offense.size + 1).times { |i| determine_move.(offense, offense_moves, i) }
dm = defense[defense_moves.index(defense_moves.max)].nil? ? [0] : defense[defense_moves.index(defense_moves.max)]
om = offense[offense_moves.index(offense_moves.max)].nil? ? [0] : offense[offense_moves.index(offense_moves.max)](defense/offence.size + 1),原因中断是在添加到数组之后。
我不确定它是否正确,但我想它的工作原理与那个循环相同。
发布于 2014-06-03 04:26:38
loop do
defense_moves << defense.count(defense[d])
...
end保证至少为defense_moves分配一个元素。
determine_move = ->move,side,i { side << move.count(move[i]) }
defense.size.times { |i| determine_move.(defense, defense_moves, i) }没有提供这样的保证。因此,defense_moves.max和defense_moves.index(defense_moves.max)都是零,这会产生错误。
发布于 2014-06-03 03:21:14
您的错误消息意味着要将零传递给[]方法。我猜它就在这条线上
defense[defense_moves.index(defense_moves.max)]或者另一个类似的。
如果defense_moves是空数组,则[].max #=> nil,如果您传递defense[nil],则会收到该错误。
https://stackoverflow.com/questions/24006220
复制相似问题