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:
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user