Project

General

Profile

Actions

Bug #13700

closed

Enumerable#sum may not work for Ranges subclasses due to optimization

Added by sos4nt (Stefan Schüßler) almost 7 years ago. Updated over 4 years ago.

Status:
Closed
Assignee:
-
Target version:
-
ruby -v:
ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-darwin15]
[ruby-core:81847]

Description

Enumerable#sum is optimized for integer ranges. Unfortunately, this can break subclasses:

class StepTwoRange < Range
  def each(&block)
    step(2, &block)
  end
end

r = StepTwoRange.new(0, 10)
r.to_a     #=> [0, 2, 4, 6, 8, 10]

r.to_a.sum #=> 30
r.sum      #=> 55

The optimization should therefore only be triggered for instances of Range and not for instances of subclasses. (or more specifically, not for subclasses overriding each)

If this behavior is intentional, it should at least be documented.

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0