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!
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.
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.
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.
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.
array.map(&:cash).inject(0, &:+)
or
array.inject(0){|sum,e| sum + e.cash }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With