Crystal, lesson 2
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.
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.
ticket_priceA 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.
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.
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 labelprice = 12
name = "Ada"
puts price * 2 # 24temperature : Float64 = 21.5lives = 3
lives = lives - 1
lives -= 1 # shorthand for the line above; += works too
puts lives # 1VAT_RATE = 20
puts 100 * VAT_RATE // 100 # 20item = "coffee"
cups = 3
puts "#{cups} cups of #{item} cost #{cups * 4} euros"Tickets: 4
Total: 51Start: 100
After deposit: 150
After withdrawal: 120