Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a mnemonic for remembering how to call ruby inject?

Tags:

ruby

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?

like image 520
djacobs7 Avatar asked Nov 24 '25 03:11

djacobs7


1 Answers

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.

like image 181
tokland Avatar answered Nov 25 '25 17:11

tokland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!