跳至內容

if var.responds_to?(...)

如果 if 的條件是 responds_to? 測試,在 then 分支中,變數的型別保證會被限制為回應該方法的型別

if a.responds_to?(:abs)
  # here a's type will be reduced to those responding to the 'abs' method
end

此外,在 else 分支中,變數的型別保證會被限制為不回應該方法的型別

a = some_condition ? 1 : "hello"
# a : Int32 | String

if a.responds_to?(:abs)
  # here a will be Int32, since Int32#abs exists but String#abs doesn't
else
  # here a will be String
end

以上方式不適用於實例變數或類別變數。若要使用這些變數,請先將它們賦值給一個變數

if @a.responds_to?(:abs)
  # here @a is not guaranteed to respond to `abs`
end

a = @a
if a.responds_to?(:abs)
  # here a is guaranteed to respond to `abs`
end

# A bit shorter:
if (a = @a).responds_to?(:abs)
  # here a is guaranteed to respond to `abs`
end