Need a simple explanation of the inject method

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

    inject takes a value to start with (the 0 in your example), and a block, and it runs that block once for each element of the list.

    1. On the first iteration, it passes in the value you provided as the starting value, and the first element of the list, and it saves the value that your block returned (in this case result + element).
    2. It then runs the block again, passing in the result from the first iteration as the first argument, and the second element from the list as the second argument, again saving the result.
    3. It continues this way until it has consumed all elements of the list.

    The easiest way to explain this may be to show how each step works, for your example; this is an imaginary set of steps showing how this result could be evaluated:

    [1, 2, 3, 4].inject(0) { |result, element| result + element }
    [2, 3, 4].inject(0 + 1) { |result, element| result + element }
    [3, 4].inject((0 + 1) + 2) { |result, element| result + element }
    [4].inject(((0 + 1) + 2) + 3) { |result, element| result + element }
    [].inject((((0 + 1) + 2) + 3) + 4) { |result, element| result + element }
    (((0 + 1) + 2) + 3) + 4
    10
    

提交回复
热议问题