Constants

Constants can be declared at the top level or inside other types. They must start with a capital letter:

  1. PI = 3.14
  2. module Earth
  3. RADIUS = 6_371_000
  4. end
  5. PI # => 3.14
  6. Earth::RADIUS # => 6_371_000

Although not enforced by the compiler, constants are usually named with all capital letters and underscores to separate words.

A constant definition can invoke methods and have complex logic:

  1. TEN = begin
  2. a = 0
  3. while a < 10
  4. a += 1
  5. end
  6. a
  7. end
  8. TEN # => 10

Pseudo Constants

Crystal provides a few pseudo-constants which provide reflective data about the source code being executed.

__LINE__ is the current line number in the currently executing crystal file. When __LINE__ is used as a default parameter value, it represents the line number at the location of the method call.

__END_LINE__ is the line number of the end of the calling block. Can only be used as a default parameter value.

__FILE__ references the full path to the currently executing crystal file.

__DIR__ references the full path to the directory where the currently executing crystal file is located.

  1. # Assuming this example code is saved at: /crystal_code/pseudo_constants.cr
  2. #
  3. def pseudo_constants(caller_line = __LINE__, end_of_caller = __END_LINE__)
  4. puts "Called from line number: #{caller_line}"
  5. puts "Currently at line number: #{__LINE__}"
  6. puts "End of caller block is at: #{end_of_caller}"
  7. puts "File path is: #{__FILE__}"
  8. puts "Directory file is in: #{__DIR__}"
  9. end
  10. begin
  11. pseudo_constants
  12. end
  13. # Program prints:
  14. # Called from line number: 13
  15. # Currently at line number: 5
  16. # End of caller block is at: 14
  17. # File path is: /crystal_code/pseudo_constants.cr
  18. # Directory file is in: /crystal_code

Dynamic assignment

Dynamically assigning values to constants using the chained assignment or the multiple assignment is not supported and results in a syntax error.

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