4

I am new to Ruby.

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

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

Sounds like they are the same.

Ry-
  • 218,210
  • 55
  • 464
  • 476
TheOneTeam
  • 25,806
  • 45
  • 116
  • 158

5 Answers5

4

||= 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
Chris Heald
  • 61,439
  • 10
  • 123
  • 137
4

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
Community
  • 1
  • 1
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
3

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
DGM
  • 26,629
  • 7
  • 58
  • 79
2

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

Leo Correa
  • 19,131
  • 2
  • 53
  • 71
  • 1
    This is wrong. It (admittedly unintuitively) expands to `a || a = 6` – Ed S. Jul 04 '13 at 04:36
  • I must admit I never thought of that expansion. @EdS. Do you have a source or a way I can check that? I updated my answer with it because it does make sense. – Leo Correa Jul 05 '13 at 16:59
  • Check one of the two duplicate topics. I have to admit, I thought the same as you a couple of years ago and answered the same question, but I was corrected by a more knowledgeable SO member. EDIT: Oops, I see you found it. – Ed S. Jul 05 '13 at 20:07
1

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.

megas
  • 21,401
  • 12
  • 79
  • 130