Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 37 ยท Syntax and Types

Variables and Constants

Learn how to create Crystal variables and constants, how type inference tracks them, why reassigning with another type creates a union, and the naming conventions to follow.

A variable is a name attached to a value. In Crystal you create one by assigning to it, with no keyword and usually no type. The compiler remembers the type for you and keeps checking that every later use makes sense. This lesson covers local variables, how reassignment affects types, constants, multiple assignment and naming conventions.

Crystal listings are read-only on this site because the compiler is not available. Where it helps, a runnable Ruby stand-in shows the closest behaviour and says where Ruby differs.

Creating variables

CRYSTAL
age = 30
price = 19.99
name = "Ada"
active = true

puts age
puts name

Each variable gets its type from the value on the right: Int32, Float64, String, Bool. To see what the compiler decided, ask for typeof:

CRYSTAL
x = 42
puts typeof(x)       # Int32
puts x.class         # Int32

typeof(x) is answered by the compiler at compile time; x.class is answered by the running program. For a plain variable they agree. We will see where they differ in union types.

You can also declare a type yourself. Use a colon:

CRYSTAL
count : Int32 = 0
ratio : Float64 = 0.5
label : String = "total"

Declaring is optional for locals. It becomes useful when you want to start with a wider type than the first value (for example, a variable that will later hold nil), or when you want to document your intention.

Reassignment and types

You may assign a new value of the same type any time:

CRYSTAL
total = 10
total = total + 5
total += 1        # shorthand for total = total + 1
puts total        # 16

Compound operators exist for the usual operations: +=, -=, *=, /=, %=, **=, ||=, &&=.

What if you assign a different type?

CRYSTAL
value = 5
value = "five"

This is legal in Crystal, unlike in most statically typed languages. After the second line the compiler knows value is a String. If the assignment sits in a branch, the variable may become a union of both types afterwards:

CRYSTAL
value = 5
if rand < 0.5
  value = "five"
end
puts typeof(value)    # (Int32 | String)

(Int32 | String) is a union type: the variable holds one or the other. You cannot call a method that only one of them has, until you narrow the type with a check. This is the foundation of Crystal's safety, and the next lessons build on it.

Here is a Ruby stand-in. Ruby lets any variable hold anything and has no union types, but you can see how the same flow produces values of two classes:

Ruby Stand-in: a variable that holds two kinds of value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Constants

A name that starts with a capital letter is a constant. Constants hold values that should not change: limits, configuration, mathematical constants.

CRYSTAL
MAX_USERS = 100
GREETING  = "Hello"
PI_ISH    = 3.14

puts MAX_USERS * 2    # 200

Rules and facts about constants:

  • Use SCREAMING_SNAKE_CASE for values and CamelCase for class and module names (they are constants too).
  • A constant cannot be reassigned: MAX_USERS = 200 later in the file is a compile error.
  • Constants are evaluated lazily and once, the first time they are needed, which lets you write initialisation code on the right-hand side.
  • You cannot define a constant inside a method body. Define it at the top level, in a class or in a module.
  • Constants are looked up by scope: Math::PI finds PI inside module Math.
CRYSTAL
module Config
  TIMEOUT = 30
  HOSTS   = ["a.example", "b.example"]
end

puts Config::TIMEOUT       # 30
puts Config::HOSTS.size    # 2

Immutability is about the name, not the object: the HOSTS array above could still have elements added, because the constant keeps pointing at the same array. Call .dup or use frozen structures if you need a value nobody can alter.

Multiple assignment

You can assign several variables in one line, or swap two values without a temporary:

CRYSTAL
a, b = 1, 2
a, b = b, a
puts "#{a} #{b}"     # 2 1

first, *rest = [10, 20, 30]
puts first           # 10
puts rest            # [20, 30]

The * collects the remaining values into an array. A method can return several values as a tuple and you can unpack them the same way.

Ruby Stand-in: swapping and splatting in Ruby

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The syntax is identical in Ruby. A difference worth knowing: Ruby only warns when you reassign a constant, while Crystal refuses to compile.

Naming conventions

Thing Style Example
Local variable, method snake_case user_count, find_user
Constant SCREAMING_SNAKE_CASE MAX_RETRIES
Class, module, struct, enum CamelCase HttpServer
Predicate method (returns Bool) ends with ? empty?
Method that changes the receiver ends with ! sort!

Variable names may contain letters, digits and underscores, cannot start with a digit, and are case-sensitive. The formatter does not rename things, so follow these rules yourself. Unused variables can start with an underscore (_), which tells readers and the compiler that you do not need the value.

Scope in brief

A local variable lives from its first assignment to the end of the block, method or file section where it was created. Methods cannot see outer locals; a block can see and modify the variables around it. Blocks have their own lesson later.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the inferred type of price = 19.99?

    A floating-point literal without a suffix is a Float64.
  2. 2. What happens if a variable is assigned an Int32 in one branch and a String in another?

    Crystal tracks both possibilities as a union and makes you handle them before using type-specific methods.
  3. 3. Which line is a valid constant definition?

    Constants start with an uppercase letter, and by convention values use SCREAMING_SNAKE_CASE.
  4. 4. What does first, *rest = [10, 20, 30] assign to rest?

    The splat collects every value after the first into an array.

Summary

  • Assign to create a variable; the compiler infers its type, and typeof shows it at compile time.
  • Reassigning a different type creates a union type when branches differ.
  • Constants start with a capital letter, cannot be reassigned and cannot be defined inside methods.
  • Multiple assignment, swapping and splats work as in Ruby.
  • Use snake_case for variables and methods, CamelCase for types, SCREAMING_SNAKE_CASE for constants.

Next: Numbers and Math