Project

General

Profile

Actions

Patch #44736

closed

Use Enumerable#sum instead of inject and explicit loops to calculate totals

Patch #44736: Use Enumerable#sum instead of inject and explicit loops to calculate totals

Added by Go MAEDA 26 days ago. Updated 18 days ago.

Status:
Closed
Priority:
Normal
Assignee:
Category:
Code cleanup/refactoring
Target version:

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_hours
  • Redmine::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 Actions #1

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:

hours = [0.1, 0.2, 0.3]

hours.inject(0) {|s, h| s + h}  # => 0.6000000000000001
hours.sum                       # => 0.6

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.

Updated by Go MAEDA 18 days ago ยท Edited Actions #2

  • Status changed from New to Closed
  • Assignee set to Go MAEDA
  • Target version changed from Candidate for next major release to 7.1.0

Committed the patch in r25466.

Actions

Also available in: PDF Atom