Need a simple explanation of the inject method

前端 未结 16 1544
天涯浪人
天涯浪人 2020-11-28 17:49
[1, 2, 3, 4].inject(0) { |result, element| result + element } # => 10

I\'m looking at this code but my brain is not registering how the number 1

16条回答
  •  生来不讨喜
    2020-11-28 18:50

    Inject applies the block

    result + element
    

    to each item in the array. For the next item ("element"), the value returned from the block is "result". The way you've called it (with a parameter), "result" starts with the value of that parameter. So the effect is adding the elements up.

提交回复
热议问题