상수

상수 (Constants)

상수는 최상위 레벨이나 다른 타입 안에서 선언할 수 있어요. 대문자로 시작해야 해요:

PI = 3.14

module Earth
  RADIUS = 6_371_000
end

PI            # => 3.14
Earth::RADIUS # => 6_371_000

컴파일러가 강제하지는 않지만, 상수는 보통 모두 대문자와 밑줄로 단어를 구분해서 이름을 지어요.

상수 정의는 메서드를 호출하고 복잡한 로직을 가질 수도 있어요:

TEN = begin
  a = 0
  while a < 10
    a += 1
  end
  a
end

TEN # => 10

의사 상수 (Pseudo Constants)

Crystal은 실행 중인 소스 코드에 대한 반영적(reflective) 데이터를 제공하는 의사 상수 몇 개를 제공해요.

__LINE__은 현재 실행 중인 Crystal 파일의 줄 번호예요. __LINE__이 기본 파라미터 값으로 쓰이면, 그 메서드를 호출한 위치의 줄 번호를 나타내요.

__END_LINE__은 호출한 블록의 end 줄 번호예요. 기본 파라미터 값으로만 쓸 수 있어요.

__FILE__은 현재 실행 중인 Crystal 파일의 전체 경로를 가리켜요.

__DIR__은 현재 실행 중인 Crystal 파일이 위치한 디렉토리의 전체 경로를 가리켜요.

# Assuming this example code is saved at: /crystal_code/pseudo_constants.cr
#
def pseudo_constants(caller_line = __LINE__, end_of_caller = __END_LINE__)
  puts "Called from line number: #{caller_line}"
  puts "Currently at line number: #{__LINE__}"
  puts "End of caller block is at: #{end_of_caller}"
  puts "File path is: #{__FILE__}"
  puts "Directory file is in: #{__DIR__}"
end

begin
  pseudo_constants
end

# Program prints:
# Called from line number: 13
# Currently at line number: 5
# End of caller block is at: 14
# File path is: /crystal_code/pseudo_constants.cr
# Directory file is in: /crystal_code

동적 대입 (Dynamic assignment)

연쇄 대입이나 다중 대입을 사용해서 상수에 값을 동적으로 대입하는 것은 지원되지 않고 구문 에러가 나요.

ONE, TWO, THREE = 1, 2, 3 # Syntax error: Multiple assignment is not allowed for constants

출처: Crystal 공식 문서

더 알아보기 (Learn more)