Need a simple explanation of the inject method

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

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

    is equivalent to the following:

    def my_function(r, e)
      r+e
    end
    
    a = [1, 2, 3, 4]
    result = 0
    
    a.each do |value|
      result = my_function(result, value)
    end
    

提交回复
热议问题