15 ms·
> If you are calling #sum on an array of non-integers then you need to provide your own initial value Why? This doesn't seem necessary, but, more importantly,
by jewbacca 10y ago
> If you are calling #sum on an array of non-integers then you need to provide your own initial value
Why? This doesn't seem necessary, but, more importantly, would be inconsistent with #inject's behaviour (if enforced).
----
http://ruby-doc.org/core-2.3.1/Enumerable.html#method-i-inject http://ruby-doc.org/core-2.3.1/Enumerable.html#method-i-inje...:
If you do not explicitly specify an initial value for memo, then the first element of collection is used as the initial value of memo
- tomstuart 10y agoI assume (but don't know) that this is an attempt to avoid returning `nil` for empty collections: `[].inject(:+)` is `nil`, but `[].sum` is `0`. Forcing the use of the additive identity every time, rather than starting with the first element of the collection, is a good way of setting people up to get the correct behaviour on empty collections, even if they don't test for that case.
- deleted 10y ago[deleted]