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.
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.
a.inject{ |sum,x| sum + x }
Or slightly shorter and faster:
a.inject(:+)
For multiplication or whatever else, just change the sign: a.inject(:*)