mirror of
https://github.com/jbranchaud/til
synced 2026-01-07 00:58:02 +00:00
Make a note about summing an empty array.
This commit is contained in:
@@ -31,4 +31,13 @@ my_hash.values.inject(:+)
|
|||||||
=> 8
|
=> 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)
|
[source](http://stackoverflow.com/questions/1538789/how-to-sum-array-of-numbers-in-ruby)
|
||||||
|
|||||||
Reference in New Issue
Block a user