I can never remember if its
array.inject{|memo,obj| block}
or
array.inject{|obj,memo| block}
Does anyone have a good trick for remembering the order?
inject/reduce is nothing but a left fold (thus called foldl/foldLeft in other languages), that's it, the recursive left-associative combination of elements with a binary operator:
(1..5).reduce(:+) == (((1 + 2) + 3) + 4) + 5 #=> true
(1..5).reduce(:-) == (((1 - 2) - 3) - 4) - 5 #=> true
So it's only natural that the accumulator is passed as the left/first argument of the block. On a right fold the accumulator would be the right/second argument.
Not really a mnemonic, but once you realize that reduce is a left fold, you won't forget where the accumulator goes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With