This is a personal memo.
Understand the meaning of expressions that have ?
(Hatena) and :
(colon) without if, as shown below.
・ X = y ==" aaa "? V: w
Expressions using ?
(Hatena) and :
(colon) are abbreviations for if else statements and are called ternary operators.
The following two processes are the same.
Normal
if conditional expression
Return value 1
else
Return value 1
end
Ternary operator
Conditional expression?Return value 1:Return value 2
Since there are three items, (1) conditional expression, (2) return value 1, and (3) return value 2, it is called a ternary operator.
python
x = 10
x == 10 ? "Yes" : "No"
=> "Yes"
If the conditional expression is false, the return value 2 is returned.
python
x = 10
x != 10 ? "Yes" : "No"
=> "No"
python
y = "aaa"
v = "Yes"
w = "No"
x = y == "aaa" ? v : w
p x
=> "Yes"
Since y ==" aaa "
is true, the previous return value v
is assigned to x
.
Recommended Posts