if !

if !

값의 참/거짓을 뒤집어서 분기하고 싶을 때가 있죠. ! 연산자는 값의 진리값(truthiness)을 부정한 Bool을 돌려줘요.

출처: Crystal 공식 문서

본문

! 연산자는 값의 진리값을 부정한 결과인 Bool을 돌려줘요.

if에서 변수, is_a?, responds_to?, nil?과 함께 쓰이면 컴파일러가 그에 맞춰 타입을 제한해요.

a = some_condition ? nil : 3
if !a
  # here a is Nil because a is falsey in this branch
else
  # here a is Int32, because a is truthy in this branch
end
b = some_condition ? 1 : "x"
if !b.is_a?(Int32)
  # here b is String because it's not an Int32
end

더 알아보기

  • !aa가 falsey이면 true, truthy이면 false를 돌려줘요. 그래서 if !a 분기에서는 a가 falsey 타입으로 좁혀져요.
  • if !b.is_a?(Int32)처럼 is_a?와 조합하면, 그 분기에서 타입을 정확히 제한할 수 있어요.
  • 진리값(truthy/falsey) 규칙은 Truthy and falsey values 문서에서 다뤄요.