El nino
El nino

Reputation: 239

calculating sum of squares in ruby

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

Please i'm try to find a way to do this.

Upvotes: 3

Views: 5310

Answers (2)

steenslag
steenslag

Reputation: 80065

a = [1,2,3,4]
p a.sum{|n| n*n} # => 30

Upvotes: 2

DNNX
DNNX

Reputation: 6255

a.map{|x| x**2}.inject(0, &:+)

Upvotes: 6

Related Questions