How to Sum Numbers in Array?

date

Published in December 11th, 2014

In developing application you may find a problem where you have to sum numbers in an array. You may feel confuse of how to do that. Here, I explain how you can solve the problem. Let's say that we have nums = [1,2,3,4,5] and the result of sum is 15.

Basically, if we're going to sum the numbers up manually it would be like nums[0] + nums[1] + nums[2] + nums[3] + nums[4] or 1 + 2 + 3 + 4 + 5. But, there's a fastest way to do this. You may use inject method.

nums = [1,2,3,4,5]
nums.inject(:+)
=> 15

You can do subtractions, multiplications too. You just have to change the + with - or *. Happy coding!