I think that Ruby’s inject method is really neat for calculating sums. But if I have to calculate an average and use inject, I always end up with something like this:
total_ranked_query_results = @results.count { |result| result.class == RankedQueryResult }
@results.inject(0.0) { |sum, result| result.class == RankedResult ? sum + result.average_precision : sum } / total_ranked_query_results
So I basically have to iterate twice to find out how many RankedResults there are in order to calculate the average.
Is there any better (rubyesque) way of avoiding this?
Either do the count and sum in the same iteration:
Or first filter the collection: