Issue #12902 has been updated by Herwin W.


Akira Tanaka wrote:
> I think [].sum should return 0.
> Returning 0 is better than nil because programmers don't need to treat empty array specially.
> This behavior is different with Enumerable#reduce which returns nil for empty array.
> 
> Also, string summation using Enumerable#sum is not good idea because it is slow.
> String#join is faster.
> So, we should not encourage Enumerable#sum for string summation.

I guess you mean Array#join

And the fact that Enumerable#sum could be used for string concatenation makes the default value of 0 pretty weird. Just imagine the following piece of code:

```ruby
a = ['']
a.sum    => ''
a.delete('')
a.sum    => 0
```
This just removes the special case of empty arrays for numeric values, but still doesn't help much with anything else (even though I agree that calculating a sum of strings is just stupid)

----------------------------------------
Feature #12902: How about Enumerable#sum uses initial value rather than 0 as default?
https://bugs.ruby-lang.org/issues/12902#change-61316

* Author: Aaron Lasseigne
* Status: Feedback
* Priority: Normal
* Assignee: 
----------------------------------------
In https://bugs.ruby-lang.org/issues/12217#note-3, Akira Tanaka, mentions that the default argument to sum is 0. This creates problems with non-numeric summations (e.g. strings). This would make the method more flexible. It also makes it behave more like `reduce`. I think using the initial value in the enumerable is less surprising than using 0.



-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>