Thank you for your reply on the Sum of Squares.

Bob Ashworth

---------- Original Message ----------------------------------
From: Kevin Smith <sent / qualitycode.com>
Reply-To: ruby-talk / ruby-lang.org
Date: Mon, 12 Mar 2001 08:17:07 +0900

>rashworth wrote:
>># The following code does not Sum the squares of the elements.
>># Define class Array for Sum of squares
>>class Array
>>  def inject(n)
>>    each { |value| n = yield(n, value) }
>>    n
>>  def sumsq
>>    inject(0) { | n, value | (n * n) + value }
>>  end
>>end
>>
>>[ 1, 2 ].sumsq          # 1 + 4 = 5
>>[ 1, 1, 0, 1 ].sumsq    # 1 + 1 + 0 + 1 = 3
>># Can you tell me what the correct code should be?
>
>Having never gotten used to the "inject" concept, 
>I would simply write:
>
>class Array
>	def sumsq
>		result = 0
>		each { | n | result += (n*n) }
>		result
>	end
>end
>
>p [1,2].sumsq
>p [1,1,0,1].sumsq
>
>Kevin
>