Patch #44736
closedUse Enumerable#sum instead of inject and explicit loops to calculate totals
Description
Some totals in Redmine are still calculated with inject(0) or an explicit loop. These were written before Enumerable#sum became available in Ruby 2.4:
TimelogHelper#sum_hoursRedmine::Helpers::TimeReport#run(@total_hours)Redmine::Helpers::Gantt#number_of_rows
The attached patch replaces them with Enumerable#sum, for example:
# Before
sum = 0
data.each do |row|
sum += row['hours'].to_f
end
sum
# After
data.sum {|row| row['hours'].to_f}
Enumerable#sum states the intent directly, which makes the code easier to read.
Files
Updated by Go MAEDA 18 days ago
As a side note, Enumerable#sum also improves the accuracy of floating-point addition. When it adds floats, it uses a compensated summation algorithm, which reduces accumulated rounding errors:
See the implementation in enum.c.
In Redmine, however, this patch does not change the totals shown in the UI. Spent hours are rounded to the minute when displayed, and floating-point rounding errors like the one above are far smaller than a minute, so they never affect the displayed values in the first place.