Mirror318
Mirror318

Reputation: 12663

Rails—what does &= do?

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 &=?

Upvotes: 9

Views: 3665

Answers (2)

mrzasa
mrzasa

Reputation: 23307

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]

Upvotes: 3

Amadan
Amadan

Reputation: 198314

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.

Upvotes: 9

Related Questions