Need a simple explanation of the inject method

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

    The syntax for the inject method is as follows:

    inject (value_initial) { |result_memo, object| block }

    Let's solve the above example i.e.

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

    which gives the 10 as the output.

    So, before starting let's see what are the values stored in each variables:

    result = 0 The zero came from inject(value) which is 0

    element = 1 It is first element of the array.

    Okey!!! So, let's start understanding the above example

    Step :1 [1, 2, 3, 4].inject(0) { |0, 1| 0 + 1 }

    Step :2 [1, 2, 3, 4].inject(0) { |1, 2| 1 + 2 }

    Step :3 [1, 2, 3, 4].inject(0) { |3, 3| 3 + 3 }

    Step :4 [1, 2, 3, 4].inject(0) { |6, 4| 6 + 4 }

    Step :5 [1, 2, 3, 4].inject(0) { |10, Now no elements left in the array, so it'll return 10 from this step| }

    Here Bold-Italic values are elements fetch from array and the simply Bold values are the resultant values.

    I hope that you understand the working of the #inject method of the #ruby.

提交回复
热议问题