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.
There are various types of
assignment operators, such as:
|+=||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.
a = b Substitute b for a.
「||」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:
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?
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.
def current_user @current_user ||= User.find_by(id: session[:user_id]) end
If the variable
@ current_user exists, it returns the originally existing
If the variable
@ current_user does not exist, find the user in
User.find_by (id: session [: user_id])and assign it to the variable
The above code can also be rewritten as follows.
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