I am new to Ruby.
What is the difference between ||
and ||=
?
>> a = 6 || 4
=> 6
>> a ||= 6
=> 6
Sounds like they are the same.
||=
will set the left-hand value to the right hand value only if the left-hand value is falsey.
In this case, both 6 and 4 are truthy, so a = 6 || 4
will set a
to the first truthy value, which is 6
.
a ||= 6
will set a
to 6 only if a
is falsey. That is, if it's nil or false.
a = nil
a ||= 6
a ||= 4
a # => 6
x ||= y
means assigningy
tox
if x is null or undefined or false ; it is a shortcut tox = y unless x
.With Ruby short-circuit operator
||
the right operand is not evaluated if the left operand is truthy.
Now some quick examples on my above lines on ||=
:
when x is undefined and n is nil
:
with
unless
y = 2
x = y unless x
x # => 2
n = nil
m = 2
n = m unless n
m # => 2
with
=||
y = 2
x ||= y
x # => 2
n = nil
m = 2
n ||= m
m # => 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With