9

To help future searches, it could also be described as "and equals" or "ampersand equals".

I found this line in the Rails source code:

attribute_names &= self.class.column_names

What is the function of &=?

mrzasa
  • 22,895
  • 11
  • 56
  • 94
Mirror318
  • 11,875
  • 14
  • 64
  • 106

2 Answers2

9

The so-called operator-assignments of the form a &= b, where & can be another binary operator, is (almost but not quite — the boolean operators are a notable exception having some corner cases where they differ) equivalent to a = a & b.

Since operators in Ruby are methods that are called on the left operand, and can be overridden, a good way to know what they are is to look at the documentation for the class of the left operand (or one of their ancestors).

attribute_names you found, given the context, is likely ActiveRecord::AttributeMethods#attribute_names, which

Returns an array of names for the attributes available on this object.

Then we can see Array#&, which performs

Set Intersection — Returns a new array containing unique elements common to the two arrays. The order is preserved from the original array.

It compares elements using their hash and eql? methods for efficiency.

Community
  • 1
  • 1
Amadan
  • 191,408
  • 23
  • 240
  • 301
3

In general case, it performs & on left-hand and right-hand sides of the assignment and then assigns the result to the left-hand side.

11 & 10
# => 10
a = 11
a &= 10
a
=> 10

a = true
a &= false
a
#=> false

In your case it performs array intersection (& operator) and then assigns the result to the attribute names:

[1,2,3] & [2,3,4]
# => [2, 3]
a &= [2,3,4]
a
#=> [2, 3]
mrzasa
  • 22,895
  • 11
  • 56
  • 94