I was just looking for something similar to reduce and read the article https://www.freecodecamp.org/news/ruby-using-the-select-map-and-reduce-methods-together-a9b2af30804b/ by Declan Meehan, but despite the comment “Please let me know if you have any questions.” there didnt seem to be a way of sending a correction in.
Anyway, the problem is with the part that reads: This one probably looks the most confusing so let’s expand it a bit.
.reduce(0){|sum, indv| sum + indv} #is the same as .reduce(:+)
And the problem is simple these are NOT equivalent! It looks good when there is something to add
irb> [1,2,3].reduce(0){|sum, indv| sum + indv}
=> 6
irb> [1,2,3].reduce(:+)
=> 6
But not with the empty array:
irb> [].reduce(0){|sum, indv| sum + indv}
=> 0
irb> [].reduce(:+)
=> nil
THIS is what its equivalent to:
[].reduce{|sum, indv| sum + indv}
Tested with RUBY_VERSION “2.5.6”