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.

2
  • For adding the elements of the array you can simply use sum method. a.sum will give you result. Commented Mar 18, 2016 at 11:30
  • 1
    In Rails and in Ruby since version 2.4.0 (released 2016-12-25) theres is Array#sum and Enumerable#sum doing just this. Commented Dec 25, 2016 at 10:54

1 Answer 1

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(:*)

Sign up to request clarification or add additional context in comments.

1 Comment

Asking and answering your own question is encouraged: blog.stackoverflow.com/2011/07/…. But in this case there are approachingly-infinite dupes so I would say that's "less encouraged."

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.