Method: Range#sum
- Defined in:
- activesupport/lib/active_support/core_ext/enumerable.rb
#sum(initial_value = 0) ⇒ Object
Optimize range sum to use arithmetic progression if a block is not given and we have a range of numeric values.
236 237 238 239 240 241 242 243 244 245 246 247 248 |
# File 'activesupport/lib/active_support/core_ext/enumerable.rb', line 236 def sum(initial_value = 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 sum = initial_value || 0 sum + (actual_last - first + 1) * (actual_last + first) / 2 else initial_value || 0 end end end |