I am new to Ruby.
What is the difference between ||
and ||=
?
>> a = 6 || 4
=> 6
>> a ||= 6
=> 6
Sounds like they are the same.
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
a ||= 6 only assigns 6 if it wasn't already assigned. ( actually, falsey, as Chris said)
a = 4 a ||= 6 => 4 a = 4 || 6 => 4
You can expand a ||= 6
as
a || a = 6
So you can see that it use a
if a
is not nil
or false
, otherwise it will assign value to a
and return that value. This is commonly used for memoization of values.
Update
Thanks to the first comment for pointing out the true expansion of the ||=
(or equal) operator. I learned something new and found this interesting post that talks about it. http://dablog.rubypal.com/2008/3/25/a-short-circuit-edge-case
Both expressions a = 6 || 4
and a ||= 6
return the same result but the difference is that ||=
assigns value to variable if this variable is nil or false.