sum = 0
self.items.each { |item| sum += item.fragments.count }
percentile = 1.0 / sum * 100
Refactorings
No refactoring yet !
op
August 16, 2010, August 16, 2010 10:54, permalink
You should use the inject method to do the sum operation.
sum = self.items.inject(0) { |sum, count| sum + count }
op
August 16, 2010, August 16, 2010 10:55, permalink
Oops, missed out on the .fragments.count..
sum = self.items.inject(0) { |sum, item| sum + item.fragments.count }
Martin Plöger
August 16, 2010, August 16, 2010 17:30, permalink
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 }
I'm pretty sure I'm not doing this right.