• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

202
Views
What does :& argument mean?

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?

over 3 years ago · Santiago Trujillo
1 answers
Answer question

0

Enumerable#inject

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
over 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error