||= and &&= Special Cases in Conditional Assignment Operators

Rosen Toshev
3 min readNov 13, 2018

--

Table of the shortcut conditional assignment operators and the full expression they translate to

a|| = b is a “conditional assignment operator”. It is considered to be a shorthand for a||a = b. There is a common misconception that only if a is defined and evaluates to false, then the right-hand side is assigned to a. However this is only partially true. If ais undefined or falsey (false or nil), then evaluate band set a to the result.

If a is undefined or falsey (false or nil), then evaluate band set a to the result.

Scenario 1 (x is defined and evaluates to false):

x = false
=> false
x ||= “hello world”
=> “hello world”

In this scenario, xis defined and evaluates to false. Following this, x gets assigned the value on the right-hand side of the ||= operator. In contrast, if a is defined and evaluates to truthy, then the right hand side of the operator is not evaluated, and no assignment takes place.

Scenario 2 (x is defined and evaluates to true):

x = true
=> true
x ||= “hello world”
=> true

In this scenario, x is true .Therefore, the ||= does not assign any value to x and x remains assigned as true.

Scenario 3 (x is defined and evaluates to 1):

x = 1
=> 1
x ||= “hello world”
=> 1

Since 1 is a truthy value in Ruby, the ||= does not reassign any value to x and xremains true.

Scenario 4 (x is defined and evaluates to 0):

x = 0
=> 0
x ||= “hello world”
x = 0
=> 0

Zero is a value and all values are evaluated to true, except for the falsey values: false and nil.

a && = b is also a conditional assignment operator. It is considered to be a shorthand for a && a = b. The a && a assigns the value on the right to the variable on the left, if the variable on the left, in this case a, is not nil or false.

If a is NOT undefined or falsey (false or nil), then evaluate band set a to the result.

Scenario 5 (x is defined and evaluates to false):

x = false
=> false
x &&= "hello world"
=> false

In this scenario, xis defined and evaluates to false. Therefore, &&= does not assign any value to x and x evaluates to false.

Scenario 6 (x is defined and evaluates to true):

x = true
=> true
x &&= "hello world"
=> "hello world"

In scenario 6, xis defined and evaluates to true. Following this, &&= does assigns the "hello world" value on the right-hand side of &&= to x.

Scenario 7 (x is defined and evaluates to 1):

x = 1
=> 1
x &&= “hello world”
=> “hello world”

Here 1 is a truthy value. Therefore, the &&= reassign the the "hello world" value on the right-hand side of &&= to x.

Scenario 8 (x is defined and evaluates to 0):

x = 0
=> 0
x &&=”hello world”
=> “hello world”

Here, there is again a reassignment since zero is a value and all values are evaluated to true, except for the falsey values: false and nil.

Additional Resources

--

--

Rosen Toshev
Rosen Toshev

No responses yet