Variables

To store a value and re-use it later, it can be assigned to a variable.

For example, if you want to say Hello Penny! three times, you don’t need to repeat the same string multiple times. Instead, you can assign it to a variable and re-use it:

  1. message = "Hello Penny!"
  2. puts message
  3. puts message
  4. puts message

This program prints the string Hello Penny! three times to the standard output, each followed by a line break.

The name of a variable always starts with a lowercase Unicode letter (or an underscore, but that’s reserved for special use cases) and can otherwise consist of alphanumeric characters or underscores. As a typical convention, upper-case letters are avoided and names are written in snake_case.

Note

The kind of variables this lesson discusses is called local variables. Other kinds will be introduced later. For now, we focus on local variables only.

Type

The type of a variable is automatically inferred by the compiler. In the above example, it’s String.

You can verify this with typeof:Class-class-method):

  1. message = "Hello Penny!"
  2. p! typeof(message)

Note

p!-macro) is similar to puts as it prints the value to the standard output, but it also prints the expression in code. This makes it a useful tool for inspecting the state of a Crystal program and debugging.

Reassigning a Value

A variable can be reassigned with a different value:

  1. message = "Hello Penny!"
  2. p! message
  3. message = "Hello Sheldon!"
  4. p! message

This also works with values of different types. The type of the variable changes when a value of a different type is assigned. The compiler is smart enough to know which type it has at which point in the program.

  1. message = "Hello Penny!"
  2. p! message, typeof(message)
  3. message = 73
  4. p! message, typeof(message)