28e9d19f948f2367b2da007e7ad858fd

I'm pretty sure I'm not doing this right.

sum = 0
self.items.each { |item| sum += item.fragments.count }
      
percentile = 1.0 / sum * 100

Refactorings

No refactoring yet !

D41d8cd98f00b204e9800998ecf8427e

op

August 16, 2010, August 16, 2010 10:54, permalink

1 rating. Login to rate!

You should use the inject method to do the sum operation.

sum = self.items.inject(0) { |sum, count| sum + count }
D41d8cd98f00b204e9800998ecf8427e

op

August 16, 2010, August 16, 2010 10:55, permalink

1 rating. Login to rate!

Oops, missed out on the .fragments.count..

sum = self.items.inject(0) { |sum, item| sum + item.fragments.count }
E8f0d6e9bc8bca695b3c5bdf75cdcc03

Martin Plöger

August 16, 2010, August 16, 2010 17:30, permalink

1 rating. Login to rate!

You don't need to pass the zero to inject. It then uses the first value of items for the initial value of "memo" (this is okay when adding the values). And you don't need to prefix items with self (a matter of taste).
Another thing is the double usage of "sum" for the block-variable and the result (it works because the outer variable is not initialized till the block finishes. If it was initialized before the block the behaviour depends on your Ruby-version 1.8 vs. 1.9).

sum = items.inject { |memo, item| memo + item.fragments.count }
A8d3f35baafdaea851914b17dae9e1fc

Adam

August 16, 2010, August 16, 2010 19:33, permalink

1 rating. Login to rate!

ActiveSupport defines Enumerable#sum, not that it saves you much in this particular case.

percentile = 1.0 / items.sum { |item| item.fragments.count } * 100

Your refactoring





Format Copy from initial code

or Cancel