Learn/Crystal/2. Values and variables
Lesson 2 of 8
Sign in

Crystal, lesson 2

Values and variables

Every value in Crystal has a type, and the compiler knows all of them before the program runs. You will meet these all the time:

You can ask for a value's type with typeof: puts typeof(3.75) prints Float64.

Variables

A variable is a name for a value. Create one by assigning to it with =:

You never have to write the type: Crystal infers it from the value. price is an Int32 because 12 is. When you want to be explicit, write the type after a colon:

Variables can be given a new value at any time:

Variable names are written in snake_case: lowercase words joined by underscores, like . They must start with a lowercase letter or an underscore.

2 exercises to try what you just read.

Exercise 1

Ticket total

Press Ctrl Enter or Check to test your code.

Exercise 2

Bank balance

Press Ctrl Enter or Check to test your code.

ticket_price

Constants

A name that starts with an uppercase letter is a constant. You assign it once, and the compiler refuses any attempt to assign it again. By convention, constants are written in SCREAMING_SNAKE_CASE:

Use constants for fixed values that should never change while the program runs, like a tax rate or the number of lives a game starts with. A reader sees immediately that the value is fixed.

Building text from values

Inside a double-quoted string, #{...} inserts the value of any expression:

You can also join strings with +, but both sides must be strings: "Cups: " + cups.to_s. to_s turns any value into a string. Interpolation does that for you, so it is usually simpler.

Further reading

  • Crystal reference: Literals
  • Crystal reference: Local variables
  • Crystal reference: Constants

A cinema sells tickets for 12 euros each, and every order pays a booking fee of 3 euros. The starter defines these as constants. For an order of 4 tickets, print:

Compute the total from the names instead of typing 51 yourself. The program reads no input.

Start a balance at 100. Print it, then add a deposit of 50 and print it, then take away a withdrawal of 30 and print it once more:

Use the same variable balance the whole way through. The program reads no input.

42        # Int32: a whole number
3.75      # Float64: a number with a decimal point
"Ada"     # String: text, in double quotes
'A'       # Char: exactly one character, in single quotes
true      # Bool: true or false
nil       # Nil: "no value"
:gold     # Symbol: a fixed name, handy as a label
price = 12
name = "Ada"
puts price * 2   # 24
temperature : Float64 = 21.5
lives = 3
lives = lives - 1
lives -= 1        # shorthand for the line above; += works too
puts lives        # 1
VAT_RATE = 20
puts 100 * VAT_RATE // 100   # 20
item = "coffee"
cups = 3
puts "#{cups} cups of #{item} cost #{cups * 4} euros"
Tickets: 4
Total: 51
Start: 100
After deposit: 150
After withdrawal: 120