I understand that in ruby we can sum the elements in an array like this
[1,2,3].sum
[<Object a: 1>, <Object a:2>].sum(&:a)
How about running a sum on multiple attributes in the array of objects. For example:
arr = [<Object a:1, b:2, ..., n:10>, <Object a:1, b:2, ..., n:10>, ... <nth Object>]
What is the most efficient way to get the sum of multiple attributes a, b, ... n?
I have tried these methods:
sum_a = arr.sum(&:a)
sum_b = arr.sum(&:b)
a, b = 0, 0
arr.each do |obj|
a += obj.a
b += obj.b
end
I am wondering if there is a better way to go about this.