Ruby array inject

前端 未结 2 1547
伪装坚强ぢ
伪装坚强ぢ 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
    

提交回复
热议问题