if var.is_a?(...)
Если условие if является проверкой is_a?, тип переменной гарантированно ограничен этим типом в ветви then.
if a.is_a?(String)
# here a is a String
end
if b.is_a?(Number)
# here b is a Number
end
Кроме того, в ветви else тип переменной гарантированно не ограничен этим типом:
a = some_condition ? 1 : "hello"
# a : Int32 | String
if a.is_a?(Number)
# a : Int32
else
# a : String
end
Обратите внимание, что в качестве проверки is_a? можно использовать любой тип, например абстрактные классы и модули.
Описанное выше работает и в том случае, если условие содержит операторы И (&&):
if a.is_a?(String) && b.is_a?(Number)
# here a is a String and b is a Number
end
Описанное выше не работает с переменными экземпляра или переменными класса. Чтобы работать с ними, сначала присвойте их значение переменной:
if @a.is_a?(String)
# here @a is not guaranteed to be a String
end
a = @a
if a.is_a?(String)
# here a is guaranteed to be a String
end
# A bit shorter:
if (a = @a).is_a?(String)
# here a is guaranteed to be a String
end
To the extent possible under law, the persons who contributed to this workhave waived
all copyright and related or neighboring rights to this workby associating CC0 with it.
https://crystal-lang.org/reference/1.2/syntax_and_semantics/if_varis_a.html