The difference between || a = b and a = a || b in ruby?

Can anyone highlight this expression. Both seem to be the same, but they are not.

a || a = b or a ||= b 

and

 a = a || b 

if

a = 4 and b = 6 , the output is always 4

This always confuse me and err. Can someone explain this?

+6
source share
2 answers
 a || a = b 

looks for a , if a is true, returns a , otherwise a = b is satisfied, that is, you assign b to a .

 a = a || b 

This is an assignment operation. Here you assign the value of a no matter what value it has. So, a is equal to a || b a || b . In the second part of the statement, you are looking for a . If its value is true, you assign it back to a itself, otherwise you assign b to a .

TL DR

a = a || b a = a || b assigns a value (depending on the condition) to a no matter what value it has.

a ||= b return a , if it is already present, else a = b

Explanation with an example:

You can think of a || a = b a || a = b as a || (a = b) a || (a = b) . Now let a = 4 and b = 6 .

Since it is an OR operation in order of priority, and since the order of operations for OR is from left to right, we start from the first a :

  # lets call this Fig. 1 a || (a = b) ^ | . (here) 

This a has a value of 4, which is the true value. Therefore, the evaluation then stops there and returns 4 . (Why? Hint: true || anything = true )

Now let's assume a = nil and b = 6 . We start from the same place again (Fig. 1). Since a is nil , which is false in Ruby, we go to the right side of the OR operation, i.e. a = b

  # lets call this Fig. 2 a || (a = b) ^ | . (here) 

Since this is an assignment operation, it will be executed, and we will finish assignment 6 a .

Returning to a = a || b a = a || b . You can consider it a = (a || b) . Obviously, in order of priority is the assignment operation. Since the order of operations for assignment is from right to left, it is first evaluated (a || b) .

  # lets call this Fig. 3 a = (a || b) ^ | . (here) 

If a = 4 and b = 6 , a || b a || b will return 4 (as discussed above). Otherwise, if a = nil and b = 6 , a || b a || b will return 6 .

Now any value is returned from this operation || receives an appointment to the first a .

  # lets call this Fig. 4 a = (a || b) ^ | . (here) 
+10
source

A common misconception is the following:

a ||= b equivalent to a = a || b a = a || b , but it behaves like a || a = b a || a = b

In a = a || b a = a || b a is defined by something by an operator in each run, whereas with a || a = b a || a = b a is set only if a is logically false (that is, if it is nil or false) because || is a short circuit.

Let me keep a simple one :

That is, if the left side || the comparison is true, there is no need to check the right side.

more links RubyInside

+4
source

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


All Articles