diff options
author | Kenta Murata <mrkn@mrkn.jp> | 2016-04-30 19:54:49 +0900 |
---|---|---|
committer | Jeremy Daer <jeremydaer@gmail.com> | 2016-04-30 18:33:39 -0700 |
commit | a678c47f6d31977e2a91cc198f115c803f0fc8e1 (patch) | |
tree | f39d09dbc6ffa7c0477493accdf80c006afc1b74 /activesupport/lib/active_support/core_ext | |
parent | 46e0666bfa502f207b8964c9d32ca01420a80a59 (diff) | |
download | rails-a678c47f6d31977e2a91cc198f115c803f0fc8e1.tar.gz rails-a678c47f6d31977e2a91cc198f115c803f0fc8e1.tar.bz2 rails-a678c47f6d31977e2a91cc198f115c803f0fc8e1.zip |
Fix initial value effects for sum along to ruby 2.4
Signed-off-by: Jeremy Daer <jeremydaer@gmail.com>
Diffstat (limited to 'activesupport/lib/active_support/core_ext')
-rw-r--r-- | activesupport/lib/active_support/core_ext/enumerable.rb | 12 |
1 files changed, 7 insertions, 5 deletions
diff --git a/activesupport/lib/active_support/core_ext/enumerable.rb b/activesupport/lib/active_support/core_ext/enumerable.rb index 941f20c19d..eae964bc2e 100644 --- a/activesupport/lib/active_support/core_ext/enumerable.rb +++ b/activesupport/lib/active_support/core_ext/enumerable.rb @@ -17,11 +17,12 @@ module Enumerable # The default sum of an empty list is zero. You can override this default: # # [].sum(Payment.new(0)) { |i| i.amount } # => Payment.new(0) - def sum(identity = 0, &block) + def sum(identity = nil, &block) if block_given? map(&block).sum(identity) else - inject(:+) || identity + sum = identity ? inject(identity, :+) : inject(:+) + sum || identity || 0 end end @@ -91,15 +92,16 @@ end class Range #:nodoc: # Optimize range sum to use arithmetic progression if a block is not given and # we have a range of numeric values. - def sum(identity = 0) + def sum(identity = nil) 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 + sum = identity || 0 + sum + (actual_last - first + 1) * (actual_last + first) / 2 else - identity + identity || 0 end end end |