Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between || and ||=? [duplicate]

Tags:

ruby

I am new to Ruby.

What is the difference between || and ||=?

>> a = 6 || 4
=> 6
>> a ||= 6
=> 6

Sounds like they are the same.

like image 368
TheOneTeam Avatar asked Dec 09 '22 14:12

TheOneTeam


2 Answers

||= 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
like image 159
Chris Heald Avatar answered Dec 11 '22 03:12

Chris Heald


x ||= y means assigning y to x if x is null or undefined or false ; it is a shortcut to x = 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
like image 34
Arup Rakshit Avatar answered Dec 11 '22 03:12

Arup Rakshit