From: Brian Candler Date: 2009-07-22T01:45:39+09:00 Subject: Re: Mean method Älphä Blüë wrote: > From my understanding of inject, using above.. > > a = first instance of array > b = subsequent instances of array No, not exactly. You are using the new 1.9 usage (possibly also 1.8.7): foo.inject { |a,b| ... } a is the first element of the array in the first iteration only. For subsequent iterations, a is the value of the previous block evaluation. It may be clearer if you stick to the old usage: foo.inject(init) { |a,b| ... } In the first invocation, a is init and b is the first element of the array. For the next invocation, a is the previous block value and b is the next element of the array. And so on. Looking at your initial code: @arr.each do |a| n += ((a - mean)**2) std = Math.sqrt(n / @size) end This is strange. You're calculating a value in every iteration and assigning it to std, but then throwing it away apart from the last one. Shouldn't this go outside the loop? n = 0 @arr.each do |a| n += ((a - mean)**2) end std = Math.sqrt(n / @size) If that's correct, then the solution becomes obvious: n = @arr.inject(0) { |accum,elem| accum + (elem-mean)**2 } std = Math.sqrt(n / @size) -- Posted via http://www.ruby-forum.com/.