Constants in Crystal

Constants in Crystal can be defined using the CONSTANT keyword. Constants are immutable once defined and can be of various data types including string, integer, and float.

Here is how you can translate the example to Crystal:

CONSTANT_S = "constant"
CONSTANT_N = 500000000
CONSTANT_D = 3e20 / CONSTANT_N

puts CONSTANT_S
puts CONSTANT_D
puts CONSTANT_D.to_i
puts Math.sin(CONSTANT_N)

Explanation:

  1. CONSTANT_S is defined as a constant string.
  2. CONSTANT_N is defined as a constant integer.
  3. CONSTANT_D is defined as a constant float using an arithmetic expression.
  4. puts is used to print values in Crystal.
  5. to_i method converts a float to an integer.
  6. Math.sin calculates the sine of an integer converted to radians.

How to Run

Save the code in a file named constants.cr and use the Crystal compiler to run it.

$ crystal run constants.cr
constant
6.0e+11
600000000000
0.28470407323754404

Now that you can define and use constants in Crystal, you can explore more about the language.