0

I have an array as follows:

a = [1,2,5,8]

I want to calculate the value of all the elements added(or multiplied) together.

newUserNameHere
  • 17,348
  • 18
  • 49
  • 79
  • For adding the elements of the array you can simply use sum method. a.sum will give you result. – Nitesh Mishra Mar 18 '16 at 11:30
  • 1
    In Rails and in Ruby [since version 2.4.0](https://github.com/ruby/ruby/blob/v2_4_0/NEWS) ([released 2016-12-25](https://www.ruby-lang.org/en/news/2016/12/25/ruby-2-4-0-released/)) theres is `Array#sum` and `Enumerable#sum` doing just this. – amoebe Dec 25 '16 at 10:54

1 Answers1

13
a.inject{ |sum,x| sum + x }

Or slightly shorter and faster:

a.inject(:+)

For multiplication or whatever else, just change the sign: a.inject(:*)

newUserNameHere
  • 17,348
  • 18
  • 49
  • 79
  • 4
    Asking and answering your own question is encouraged: http://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/. But in this case there are approachingly-infinite dupes so I would say that's "less encouraged." – roippi Feb 17 '14 at 22:33