Is there an additional shortcut injection

I recently ran into this problem:
I have always used injection like this (I knew the (0) part is optional and could 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 problem I found a good introduction article but didn't mention what I tried ....
Can someone explain to me or give some information about these injection commands I just used?

+3


source to share


1 answer


From the doc Enumerable#inject

:

... If you specify a symbol instead, then each item in the collection will be passed to the named memo method. In any case, the result becomes a new memo value. At the end of the iteration, the final memo is the return value for the method.

If you do not explicitly provide a start value for the memo, then the first item in the collection is used as the start value for the memo.

So, if you specify a character, it treats it as a method name and calls that method on every enum element replacing memo as above. Now math operators (+ - * /) are just methods, nothing else. These lines give an identical result:

13 + 23 # => 36
13.+(23) # => 36
13.send(:+, 23) # => 36

      



When you pass the symbol inject

or reduce

, it uses the third form to dynamically apply that operator to elements:

[1,2,3].inject(:+) # => 6

      

This shorthand can also be used with methods other than operators:

[{"a"=>1}, {"b"=>2}].inject(:merge) # => {"a"=>1, "b"=>2} 

      

+6


source







All Articles