Usually we use the following form when we write code, construct nested data, or initialize a variable:
A | | = [] ; A = B | | C A = a | | []
This form ensures that the variables are initialized when they are accessed, giving us a great deal of flexibility in structuring the data, and this is the application of NULL pointer protection in Ruby.
To understand how null pointer protection works, from Ruby True and false values and | | Two aspects of operation method:
First, the other values are considered true in Ruby except that nil and false are false.
Secondly, on the surface | | The operator returns True when either of the two expressions is true, and two is false to return fasle; in Ruby, the value of the expression is returned, and if the value of expression 1 is not nil or false, the value of the expression 1 is returned ( is considered true)if the value of expression 1 is nil or false, then | | The operator determines whether the value of the expression 2 is nil or false, and returns the value of Expression 2 ( considered true)if it is not nil or false, otherwise it means that the values of both expressions are nil or false. This returns nil or false (that is, the value of expression 2).
Note: the values returned in the above are the expressions, not the Boolean values true or FALSE, but the values of these expressions are considered false or true.
For example: if a | | b #代码block End
Suppose a = "str" b is any value, a | | b Returns the value of a "str" because the value of a is not nil or false but a string, so the string is interpreted as true, then the IF condition statement is similar to if true
Suppose A = nil or false B = 12.5, a | | b Returns the value 12.5 of B, because the value of a is nil after false, so the value of B is determined, and the value of B is 12.5, so the string is interpreted as true, then the IF condition statement is similar to if true
Suppose A = nil or false B = nil or fals, a | | b returns the value nil or false for B, and the value of B is interpreted as false, at which point the IF condition statement is similar to if False
On seeing a = a | | [] This kind of writing may be asked: a here is not defined Ah, will report undefined local variables or methods of the error; in fact, the Declaration and assignment of variables in Ruby is mixed, c = 1 contains the declaration of the variable C and the assignment of variable C 1, that is, the interpreter encountered when executing into this line of code = , then = the variable on the left is declared (that is, declared as a variable) and the variable is not assigned a value, so the value of the variable is nil and therefore returns [].
For example:
A = 5 If False #变量定义未赋值
A # = Nil
About null pointer protection in Ruby (| | =