I don't understand the :&
argument for the inject method in this example:
[1, 2].map do |id|
my_custom_method(MyModel.find(id))
end).inject(:&).map(&:category).uniq.compact.sort
:
makes sense to me:
[1, 2, 3].inject(: )
is the same as:
[1, 2, 3].inject { |sum, number| sum number }
What does :&
mean, as in the example above?
CodePudding user response:
If you specify a symbol instead, then each element in the collection will be passed to the named method of memo
So &
is just Integer#& method
Bitwise AND; each bit in the result is 1 if both corresponding bits in self and other are 1, 0 otherwise
[7, 5].inject(:&) # => 5
It's the same as
7 & 5 # => 5
And how it works
7.to_s(2) # => "111"
5.to_s(2) # => "101"
7: 1 1 1
& & &
5: 1 0 1
--------
5: 1 0 1