程序在 repl.it 中工作,但在代码战争中出现"undefined method"错误



我一直在做一个codewars挑战,我想提交它,我的代码在 repl.it 中工作并通过了所有测试,但是当我在codewars shell中运行它时,我收到此错误:

queue_time': undefined method `max' for nil:NilClass (NoMethodError)
    from `block in'
    from `block in describe'
    from  `measure'
    from  `describe'
    from  `'

这是代码:

def queue_time(customers, n)
  total_queue = [] 
  i = 0 
  while i < n
    total_queue << [customers[i]]
    i += 1 
  end 
  open_queue_index = total_queue.index {|x| x == total_queue.min}
  k = n  
  while k < customers.length
    array_summed = []
    total_queue[open_queue_index] << customers[k]
      total_queue.each_index do |index|
        array_summed << total_queue[index].reduce(:+)
      end 
    open_queue_index = array_summed.index {|x| x == array_summed.min}
    k += 1 
  end 
  array_summed.max
end

为什么Codewars不理解.max方法?

如果customers数组为空,您的方法将中断。如果该数组为空,则该方法将永远不会进入while k < customers.length块,并且永远不会初始化array_summed

然后在最后一行,array_summed.max基本上就像在说nil.max

您是否在 repl.it 和代码战争中传递不同的customers数组?如果您在代码战争中测试的数组为空,则这将中断。

array_summed 未初始化。

while false
  array_summed = [] # initialized
end
array_summed # is nil because it was never initialized.
'

''

相关内容

最新更新