Ruby array inject

前端 未结 2 1529
伪装坚强ぢ
伪装坚强ぢ 2021-01-16 15:35

I am trying to log the average running time of 10 threads by using the inject method but it\'s giving me this error:

undefined method `+\' for #

        
相关标签:
2条回答
  • 2021-01-16 16:23

    You need to provide an initial value for inject in this case, since if you don't, the initial value is simply the first element in the array:

    puts threads.inject(0) { |sum, e| sum + e.value}.to_f / threads.size
    
    0 讨论(0)
  • 2021-01-16 16:33

    You didn't provide an initial value for sum in

    threads.inject() { |sum, e| sum + e.value}.to_f / threads.size
    

    Fix it with

    threads.inject(0) { |sum, e| sum + e.value}.to_f / threads.size
    
    0 讨论(0)
提交回复
热议问题