Rails—what does &= do?

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.


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]