Need a simple explanation of the inject method

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

    The number you put inside your () of inject represents a starting place, it could be 0 or 1000. Inside the pipes you have two place holders |x, y|. x = what ever number you had inside the .inject('x'), and the secound represents each iteration of your object.

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

    1 + 5 = 6 2 + 6 = 8 3 + 8 = 11 11 + 4 = 15

提交回复
热议问题