Variables
For example, if you want to say 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:
This program prints the string 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 .
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.
The type of a variable is automatically inferred by the compiler. In the above example, it’s String.
You can verify this with :Class-class-method):
p!-macro) is similar to 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:
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.