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