How to calculate averages using the Ruby Inject function

I think the Ruby method is injectreally neat for calculating sums. But if I need to calculate the average and use inject, I always get 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

Therefore, I basically have to iterate twice to find out how much RankedResultsthere is to calculate the average.

Is there a better (rubic) way to avoid this?

+3
source share
1 answer

Or do the calculation and the amount in the same iteration:

tmp = @results.inject([0.0, 0]) { |sum, result|
    if RankedResult === result
        [sum.first + result.average_precision, sum.last+1]
    else
        sum
    end
}
tmp.first / tmp.last

Or filter the collection first:

tmp = @results.filter { |result| RankedResult === result }
tmp.inject(0.0) { |sum, result| sum+result.avergage_precision } / tmp.length
+3
source

Source: https://habr.com/ru/post/1788154/


All Articles