Method: Range#sum

Defined in:
lib/active_support/core_ext/enumerable.rb

#sum(identity = 0) ⇒ Object

Optimize range sum to use arithmetic progression if a block is not given and we have a range of numeric values.



68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/active_support/core_ext/enumerable.rb', line 68

def sum(identity = 0)
  if block_given? || !(first.is_a?(Integer) && last.is_a?(Integer))
    super
  else
    actual_last = exclude_end? ? (last - 1) : last
    if actual_last >= first
      (actual_last - first + 1) * (actual_last + first) / 2
    else
      identity
    end
  end
end