Skip to content

Instantly share code, notes, and snippets.

@priyankamk
Last active May 6, 2019 05:17
Show Gist options
  • Save priyankamk/54056b96e1e5b2f04cc650feaa90d416 to your computer and use it in GitHub Desktop.
Save priyankamk/54056b96e1e5b2f04cc650feaa90d416 to your computer and use it in GitHub Desktop.
How to add elements or integer or values in an array - RUBY

How to add integer in an array using inject - reduce family.

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

inject

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment