Need a simple explanation of the inject method

前端 未结 16 1516
天涯浪人
天涯浪人 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:40

    The code iterates over the four elements within the array and adds the previous result to the current element:

    • 1 + 2 = 3
    • 3 + 3 = 6
    • 6 + 4 = 10

提交回复
热议问题