Reputation: 239
Is there anyway i can calculate the sum of the square of objects in an array
a=[1,2,3,4] sum of square = 1+4+9+16
a=[1,2,3,4]
sum of square = 1+4+9+16
Please i'm try to find a way to do this.
Upvotes: 3
Views: 5310
Reputation: 80065
a = [1,2,3,4] p a.sum{|n| n*n} # => 30
Upvotes: 2
Reputation: 6255
a.map{|x| x**2}.inject(0, &:+)
Upvotes: 6