Need a simple explanation of the inject method

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

    What they said, but note also that you do not always need to provide a "starting value":

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

    is the same as

    [1, 2, 3, 4].inject { |result, element| result + element } # => 10
    

    Try it, I'll wait.

    When no argument is passed to inject, the first two elements are passed into the first iteration. In the example above, result is 1 and element is 2 the first time around, so one less call is made to the block.

    0 讨论(0)
  • 2020-11-28 18:47

    This code doesn't allow the possibility of not passing a starting value, but may help explain what's going on.

    def incomplete_inject(enumerable, result)
      enumerable.each do |item|
        result = yield(result, item)
      end
      result
    end
    
    incomplete_inject([1,2,3,4], 0) {|result, item| result + item} # => 10
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题