Need a simple explanation of the inject method

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

    This is a simple and fairly easy to understand explanation:

    Forget about the "initial value" as it is somewhat confusing at the beginning.

    > [1,2,3,4].inject{|a,b| a+b}
    => 10
    

    You can understand the above as: I am injecting an "adding machine" in between 1,2,3,4. Meaning, it is 1 ♫ 2 ♫ 3 ♫ 4 and ♫ is an adding machine, so it is the same as 1 + 2 + 3 + 4, and it is 10.

    You can actually inject a + in between them:

    > [1,2,3,4].inject(:+)
    => 10
    

    and it is like, inject a + in between 1,2,3,4, making it 1 + 2 + 3 + 4 and it is 10. The :+ is Ruby's way of specifying + in the form of a symbol.

    This is quite easy to understand and intuitive. And if you want to analyze how it works step by step, it is like: taking 1 and 2, and now add them, and when you have a result, store it first (which is 3), and now, next is the stored value 3 and the array element 3 going through the a + b process, which is 6, and now store this value, and now 6 and 4 go through the a + b process, and is 10. You are essentially doing

    ((1 + 2) + 3) + 4
    

    and is 10. The "initial value" 0 is just a "base" to begin with. In many cases, you don't need it. Imagine if you need 1 * 2 * 3 * 4 and it is

    [1,2,3,4].inject(:*)
    => 24
    

    and it is done. You don't need an "initial value" of 1 to multiply the whole thing with 1.

提交回复
热议问题