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