ar =[1000000001, 1000000002, 1000000003, 1000000004, 1000000005]
ar.inject(0) {|sum, x| sum + x}
5000000015
or simple method
ar.sum
ar.inject(0) => starts from 0 index to add |sum, x| => sum will be starting index 0 and x will be the ending index 10 sum + x => when it adds both from 1st to last => result will be 5000000015
The official Ruby documentation defines inject as: Combines all elements of enum by applying a binary operation, specified by a block or a symbol that names a method or operator. ... This method returns an updated hash as our new accumulator.
You can think of the first block argument as an accumulator: the result of each run of the block is stored in the accumulator and then passed to the next execution of the block. In the case of the code shown above, you are defaulting the accumulator, result, to 0. Each run of the block adds the given number to the current total and then stores the result back into the accumulator. The next block call has this new value, adds to it, stores it again, and repeats.
At the end of the process, inject returns the accumulator, which in this case is the sum of all the values in the array, or 10