← Back to Ruby Operators

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.

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.

References