Need a simple explanation of the inject method

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

    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
    

提交回复
热议问题