The assignment operator
is an operator for assigning a value to a variable.
The article below explains it in an easy-to-understand manner, so if you don't understand it, please read it.
https://wa3.i-3-i.info/word18049.html
There are various types of assignment operators
, such as:
symbol | meaning |
---|---|
= | Substitution |
+= | Add and substitute |
-= | Subtract and substitute |
*= | Multiply and substitute |
/= | Divide and substitute |
%= | Modulo and substitute |
**= | Exponentiation and substitution |
In the assignment operator,「||=」
Such assignment operators also exist.
「="When"||Is a combined operator.
" = "
Means assignment. As mentioned above, it is a kind of assignment operator.
python
a = b
Substitute b for a.
continue,「||」
Is an operator that returns true if either condition is met. (Meaning OR.)
This is called the ** logical operator **.
When used with an if statement, it looks like this:
python
if a || b #Returns true if a or b is true and true.
#If a or b is true
else
#If both are false
end
What will happen if these two operators are combined?
python
a ||= b
Substitute b if a is false or undefined.
Also a= (a || b)Has the same meaning as.
It will behave like this. The actual example sentences are shown below.
python
def current_user
@current_user ||= User.find_by(id: session[:user_id])
end
If the variable @ current_user
exists, it returns the originally existing @ current_user
.
If the variable @ current_user
does not exist, find the user inUser.find_by (id: session [: user_id])
and assign it to the variable @ current_user
.
The above code can also be rewritten as follows.
python
def current_user
@current_user = @current_user || User.find_by(id: session[:user_id])
end
Rails tutorial Chapter 8 https://railstutorial.jp/chapters/log_in_log_out?version=4.2#cha-log_in_log_out
Recommended Posts