if¶
如果 if
的條件為真值,則會評估給定的分支。否則,如果存在 else
分支,則會評估該分支。
a = 1
if a > 0
a = 10
end
a # => 10
b = 1
if b > 2
b = 10
else
b = 20
end
b # => 20
要撰寫 if-else-if 的鏈,您可以使用 elsif
。
if some_condition
do_something
elsif some_other_condition
do_something_else
else
do_that
end
在 if
之後,變數的類型取決於兩個分支中使用的表達式類型。
a = 1
if some_condition
a = "hello"
else
a = true
end
# a : String | Bool
b = 1
if some_condition
b = "hello"
end
# b : Int32 | String
if some_condition
c = 1
else
c = "hello"
end
# c : Int32 | String
if some_condition
d = 1
end
# d : Int32 | Nil
請注意,如果變數在其中一個分支中宣告,但未在另一個分支中宣告,則在 if
的結尾,它也會包含 Nil
類型。
在 if
的分支中,變數的類型是在該分支中賦值的類型,或者如果未重新賦值,則為分支之前的類型。
a = 1
if some_condition
a = "hello"
# a : String
a.size
end
# a : String | Int32
也就是說,變數的類型是最後賦給它的表達式類型。
如果其中一個分支永遠無法到達 if
的結尾,例如在 return
、next
、break
或 raise
的情況下,則在 if
的結尾不會考慮該類型。
if some_condition
e = 1
else
e = "hello"
# e : String
return
end
# e : Int32