Reputation: 941
I don't get why
(var ||= []) << 1
works as expected but
(var ||= true) = false
doesn't.
Could anyone explain why it doesnt work and what is going on here?
Upvotes: 2
Views: 215
Reputation: 3895
a ||= b
behaves like a || a = b
.
An assignment returns the assigned value, i.e., var = true
returns true
.
var ||= true
will evaluate to the assignment var = true
, because var
is undefined at that point. If var
is defined and its value is true
, it will return the value of var
, that is true
; if it's false, it will return the value of true
, which is true
.
var ||= []
returns []
, and your first expression evaluated to [] << 1
, which is legal.
However, your second expression evaluates to true = false
, which throws a compile error.
tl;dr
(var ||= []) << 1
⟺ (var = []) << 1
⟺ [] << 1
✔
(var ||= true) = false
⟺ (var = true) = false
⟺ true = false
✘
Upvotes: 12
Reputation: 5545
In the first case you have an object, and you uses its <<
method.
In the second case you have an assignment, where the right expression must be assigned to a variable on the left, not to an object or expression.
Upvotes: 3