Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum properties of the objects within an array in Ruby

I understand that in order to sum array elements in Ruby one can use the inject method, i.e.

array = [1,2,3,4,5]; puts array.inject(0, &:+)  

But how do I sum the properties of objects within an object array e.g.?

There's an array of objects and each object has a property "cash" for example. So I want to sum their cash balances into one total. Something like...

array.cash.inject(0, &:+) # (but this doesn't work) 

I realise I could probably make a new array composed only of the property cash and sum this, but I'm looking for a cleaner method if possible!

like image 589
Spike Fitsch Avatar asked Jun 30 '12 09:06

Spike Fitsch


People also ask

How do you sum values in array of objects?

To sum a property in an array of objects:Initialize a sum variable, using the let keyword and set it to 0 . Call the forEach() method to iterate over the array. On each iteration, increment the sum variable with the value of the object.

How do you sum all elements in an array Ruby?

Use Array#inject to Sum an Array of Numbers in Ruby To calculate the sum of an array in Ruby versions before 2.4. 0, we must use inject or its alias reduce . inject is a function that takes an initial value and a block. The accumulation is the first block argument, and the current number is the second.

How do you find the number of elements in an array in Ruby?

Ruby | Array count() operation Array#count() : count() is a Array class method which returns the number of elements in the array. It can also find the total number of a particular element in the array. Syntax: Array. count() Parameter: obj - specific element to found Return: removes all the nil values from the array.

How do you sum a list in Ruby?

The sum() of enumerable is an inbuilt method in Ruby returns the sum of all the elements in the enumerable. If a block is given, the block is applied to the enumerable, then the sum is computed. If the enumerable is empty, it returns init. Parameters: The function accepts a block.


1 Answers

array.map(&:cash).inject(0, &:+) 

or

array.inject(0){|sum,e| sum + e.cash } 
like image 131
Yuri Barbashov Avatar answered Sep 30 '22 12:09

Yuri Barbashov