I have an array personas[]
that contains the data of many people, in each hash, that is, each person has their own hash. I want to add the values of all the ages, and tried several things without results.
persona = {nombre:a, edad:b, comuna:c, género:d }
You can add the ages like this:
This works like this:
First you have the array
personas
that contains the hashes of each person, then we iterate through that array using the methodmap
to get the age of each person withpersona[:edad]
and finally we applyinject(:+)
that is going to sum all the values that we passed, in this case, all the ages.It should be added that Ruby from the version
2.4
adds the methodEnumerable#sum
, which as the name indicates, adds all the elements of aEnumerable
:Greetings.
Another option is to use
reduce
(orinject
) with a block, which is more efficient since the array is traversed only once: