Sum of an array
Question: So in Python `sum([])` will yield 0, which is pretty important.

Whereas in ruby `[].reduce(:+)` will give nil, of course the ternary operator
isn't a replacement, because:

    
    
    (my_complicated_mapping).empty? ? 0 : (my_complicated_mapping).reduce(:+) 
    

Will call `my_complicated_mapping` twice. Therefore the obvious method is:

    
    
    res = my_complicated_mapping
    res = (res.empty? ? 0 : res.reduce(:+))
    

I think there must be a neater way to do this though.


Answer: With reduce you can specify the initial value as the first parameter e.g.

    
    
    my_complicated_mapping.reduce(0, :+)
    

then if the list is empty you'll get 0 instead of `nil`. You can check the
different alternative ways of using `reduce` [here](http://ruby-
doc.org/core-2.2.0/Enumerable.html#method-i-reduce).

or if using a block for `reduce` it would be:

    
    
    my_complicated_mapping.reduce(0) { |sum, n| sum + n }
    

i.e. a single parameter with with initial value and supplying your block.

It's important to understand _why_ `reduce` returns `nil` in the case of the
empty array: If you don't specify an explicit initial value for memo, then the
first element of the array is used as the initial value of memo, which of
course doesn't exist in the empty case.

