The difference between || and || =?

I am new to Ruby.

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

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

They seem to be the same.

+4
source share
5 answers

||= will set the left value to the right value only if the left value is false.

In this case, both 6 and 4 are true, therefore a = 6 || 4 a = 6 || 4 sets a to the first truth value, which is 6 .

a ||= 6 set a to 6 only if a false. That is, if it is zero or false.

 a = nil a ||= 6 a ||= 4 a # => 6 
+4
source

x ||= y means assigning y to x if x is null or undefined or false; it is short for x = y unless x .

With Ruby Short Circuit Operator || the right operand is not evaluated if the left operand is right.

Now a few quick examples on my lines above 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 

c =||

 y = 2 x ||= y x # => 2 n = nil m = 2 n ||= m m # => 2 
+4
source

a || = 6 only assigns 6 if not already assigned. (actually a lie, as Chris said)

  a = 4
 a || = 6
 => 4

 a = 4 ||  6
 => 4
+3
source

You can expand a ||= 6 as

 a || a = 6 

So you can see that it uses a if a not nil or false , otherwise it assigns the value a and returns that value. This is commonly used to memoize values.

Update

Thanks to the first comment indicating the true extension 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

+2
source

Both expressions a = 6 || 4 a = 6 || 4 and a ||= 6 return the same result, but the difference is that ||= assigns a value to a variable if this variable is nil or false.

+1
source

Source: https://habr.com/ru/post/1489612/


All Articles