1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00

Make a note about summing an empty array.

This commit is contained in:
jbranchaud
2015-02-06 22:21:43 -06:00
parent 9b22766def
commit 142a3bfded

View File

@@ -31,4 +31,13 @@ my_hash.values.inject(:+)
=> 8
```
To take this one step further, let's consider what will happen with an empty
array. The above approach will produce `nil`. If we want `0` when the list
is empty, then tell `#inject` to do just that
```ruby
[].inject(0, :+)
=> 0
```
[source](http://stackoverflow.com/questions/1538789/how-to-sum-array-of-numbers-in-ruby)