App Academy

How does Array.inject(:&) work?


I’m trying to work through the software engineering foundations course before my cohort start date on August 31. I was comparing my solutions to the answers for “nauseating numbers” under W1D3 when I noticed the answer for mutual_factors used Array.inject(:&) and I was hoping to get an explanation of how this worked. I have a basic understanding of inject from the notes/lecture on W1D1 for this course, but this seems to be a new use of inject that wasn’t covered.

I get that in this case inject is being passed the symbol “:&” but I’m not sure what this symbol represents and I don’t really comprehend how inject works when it’s only passed a symbol. The documentation for inject in this case references a method called memo, but that seems to be linked to the underlying C++ and I don’t really follow.

Any explanation around how inject works in this case and what the :& symbol does would be much appreciated. Also, is there some resource available that lists and defines all the symbols native to ruby?

Thanks in advance!

I was stuck in this same solution and I think I found out something. Taking an example of inject,
[3, 6, 10, 13].inject(:+) => (((3 + 6) + 10) + 13) => 32, we are adding up the elements using (:+). If we use the same logic then in the solution inject(:&) recieves a 2d array where each single array consists of factors of the numbers provided and we are performing intersection(:&) between the first two arrays in the 2d arrays. Like :+, where + is an operator, & is also an operator. I hope this helps.

1 Like

Thank you! Yeah, at the time I wasn’t aware of the notation of passing a symbol in to inject since I hadn’t learned about symbols at that point.

For anyone reading this, symbols in Ruby are very similar to strings. Whereas strings are notated by quotes, symbols start with a colon.

Inject often has a common pattern that’s something like:
array.inject |accumulator, element| do
accumulator = accumulator OPERATION element

where “OPERATION” is some function/method. The symbol notation allows you to use a shorthand where you just pass OPERATION in as a symbol to Array#inject, which acts the same as the above.

1 Like

Thank you for the reply. I understand inject much better now!