Double-Pipe Equals (Ruby)
When assigning one variable to another
If a = 1
and b = nil
, and you set b = a
, then the value of b
will be 1
, because you have assigned b
to have the value of a
.
If a = 1
and b = 2
, and you set b = a
, then the value of b
will also be 1
, because you have assigned b
to have the value of a
, and this replaced the previous value of b
, which was 2
.
With the regular assignment operator (=
), it doesn’t matter what value a variable previously had; when the variable is assigned a new value, it always takes on that value.
The ||=
(Double-Pipe Equals) operator assigns a value to a variable only if the variable currently has a nil
value.
If a = 1
and b = nil
, and you set b ||= a
, then the value of b
will be 1
, because b
previously had a nil
value, so it is able to be assigned the value of a
using the ||=
operator.
If a = 1
and b = 2
, and you set b ||= a
, then the value of b
will remain 2
, because b
already has a non-nil
value, so the ||=
operator is not able to assign the value of a
to it.