I recently ran into this issue:
I’ve always used inject like so (i knew that (0) part is optional and can be omitted)
array = [13,23,13]
#=> [13, 23, 13]
array.inject(0) { |sum,i| sum+i }
#=> 49
By chance i found out that you can use:
array.inject(:+)
#=> 49
array.inject(:-)
#=> -23
array.inject(:*)
#=> 3887
array.inject(:/)
#=> 0
Googling on the issue i found a nice article on inject, but no mentioning there about what i’ve tried….
Can anyone explain to me or give some info about these inject commands that I’ve just used?
From the doc on
Enumerable#inject:So, if you specify a symbol, it treats it as a method name and invokes this method on every element of the enumerable, replacing memo as stated above. Now, the math operators (+-*/) are just methods, nothing else. These lines produce identical result:
When you pass a symbol to
injectorreduceit uses the third form to dynamically apply that operator to elements:This shorthand can be used with methods other than operators as well: