And Equals Operator
The &&=
operator is a conditional assignment operator. It assigns the right-hand value to the left-hand variable if the left-hand value is truthy.
Not what you're looking for? The &
symbol is used in several syntactically distinct ways in Ruby. Head over to the Ampersand page to get a lay of the land.
This is one of many operators where =
gets tacked on to the end as a shorthand. These two code snippets are equivalent.
Using boolean and followed by an assignment:
who = 'world'
who = who && 'friend'
puts "Hello, #{who}!" #=> Hello, friend!
Using the &&=
operator:
who = 'world'
who &&= 'friend'
puts "Hello, #{who}!" #=> Hello, friend!
The &&=
operator is not used very commonly. The ||=
operator, on the other hand, is used quite a bit, especially in Rails code.